-
Notifications
You must be signed in to change notification settings - Fork 0
/
crf_absa16.py
1469 lines (1229 loc) · 45.7 KB
/
crf_absa16.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from lxml import etree
from nltk.tokenize.casual import TweetTokenizer
import text_utils
import random
import math
from copy import deepcopy
import os.path
import codecs
from subprocess import Popen, PIPE
import re
import nltk
import tempfile
import treetaggerwrapper
import string
def extract_class_for_CRF(ipath, tokenizer=TweetTokenizer()):
"""Extract class information for all tokens #E/A.
Args:
ipath: The XML file to parse.
tokenizer: The tokenizer to use.
Returns:
Returns a list of Sentence were dict consist of features
to learn from by the CRF.
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
tree = etree.parse(ifile)
ret = []
for review in tree.getroot().iterchildren():
for sentences in review.iterchildren():
for sentence in sentences.iterchildren():
Sentence = {}
text = ''
opinions = []
for element in sentence.iterchildren():
if element.tag == 'text':
text = element.text
if element.tag == 'Opinions':
for opinion in element.iterchildren():
opinions.append(opinion)
if text is None: # some texts might be missing, skip it
text = 'none'
Sentence['raw_text'] = text
Sentence['opinions'] = opinions
Sentence['tokens'] = []
Sentence['tokens'] = [token for token in tokenizer.tokenize(text) if token.strip() != '']
Sentence['spans'] = text_utils.spans_retrieval(Sentence['raw_text'],
' '.join(Sentence['tokens']))
beg_class = False
Sentence['tokens_class'] = []
for (f1, t1) in Sentence['spans']:
w_class = 'O'
for opinion in opinions:
# EC: Are we sure we can extract from/to?
f2, t2 = opinion.get('from'), opinion.get('to')
if f2 is not None and t2 is not None:
f2, t2 = int(f2), int(t2)
if f1 >= f2 and t1 <= t2:
# Are we in the middle of a class segment?
if beg_class:
prefix = 'I'
else:
prefix = 'B'
beg_class = True
w_class = prefix # + '_' + opinion.get('category')
break
else:
beg_class = False
Sentence['tokens_class'].append(w_class)
ret.append(Sentence)
return ret
def write_class_for_CRF(Sentences, w_path, c_path, s_path):
"""Write the output of extract_class_for_CRF to be processed by Wapiti.
$ paste w_path c_path > wapiti.crf;
Args:
Sentences: A list of Sentence as returned by extract_class_for_CRF.
w_path: The file to write the words (surface form).
c_path: The file to write the class.
s_path: The file to write the spans.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
with codecs.open(w_path, 'w', 'utf-8') as wfile:
with codecs.open(c_path, 'w', 'utf-8') as cfile:
with codecs.open(s_path, 'w', 'utf-8') as sfile:
for Sentence in Sentences:
for (token, token_class, span) in zip(Sentence['tokens'],
Sentence['tokens_class'],
Sentence['spans']):
cfile.write(token_class + '\n')
wfile.write(token + '\n')
sfile.write(str(span[0]) + ' ' + str(span[1]) + '\n')
cfile.write('\n')
wfile.write('\n')
sfile.write('\n')
def write_tokenized_text(Sentences, tpath):
"""Write the tokenized text to tpath.
Args:
Sentences: A list of Sentence (see extract_class_for_CRF).
tpath: The path to write the tokens.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
with codecs.open(tpath, 'w', 'utf-8') as tfile:
for Sentence in Sentences:
tokens = []
for token in Sentence['tokens']:
tokens.append(token.replace(' ', ''))
tfile.write(' '.join(tokens))
tfile.write('\n')
def split_dataset(ipath, parts=10, n_train=9, n_test=1,
odir='expe/', shuffle=True):
"""Split the dataset into train/test + gold.
Args:
ipath: Path of the dataset.
parts: Number of parts to split the dataset into.
n_train: How many parts should be assigned to the training set.
n_test: How many parts should be assigned to the testing set.
odir: Output directory.
shuffle: Whether the dataset should be shuffled.
Returns:
The sentence indexes of each dataset.
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
tree = etree.parse(ifile)
reviews = tree.getroot().getchildren()
# Should we shuffle the dataset before breaking it into parts?
if shuffle:
random.shuffle(reviews)
r = []
s_idx = 0
r_idx = 0
for review in reviews:
s_indexes = []
for sentences in review.iterchildren():
for sentence in sentences.iterchildren():
s_indexes.append(s_idx)
s_idx = s_idx + 1
r.append([review, r_idx, s_indexes])
r_idx = r_idx + 1
reviews = r
reviews_parts = list(split(reviews, parts))
ret = []
train_indexes = []
test_indexes = []
splitted_dataset = split_lst(reviews_parts, [n_train, n_test])
for i in range(parts):
(train_l, test_l) = splitted_dataset[i]
train = []
train_indexes.append([])
for part in train_l:
for (el, r_idx, s_idx) in part:
train.append(el)
train_indexes[i].extend(s_idx)
gold = []
test_indexes.append([])
for part in test_l:
for (el, r_idx, s_idx) in part:
gold.append(el)
test_indexes[i].extend(s_idx)
test = deepcopy(gold)
ret.append([train, test, gold])
# Remove Opinions node in the test dataset
for review in test:
for sentences in review.iterchildren():
for sentence in sentences.iterchildren():
for element in sentence.iterchildren():
if element.tag == 'Opinions':
sentence.remove(element)
for (reviews, oname) in [(train, 'train.xml'),
(test, 'test.xml'),
(gold, 'gold.xml')]:
root = etree.Element('Reviews')
for review in reviews:
root.append(review)
if not os.path.exists(os.path.join(odir, str(i))):
os.mkdir(os.path.join(odir, str(i)))
opath = os.path.join(odir, str(i), oname)
with open(opath, 'wb') as ofile:
ofile.write(etree.tostring(root, encoding='UTF-8',
pretty_print=True,
xml_declaration=True))
return train_indexes, test_indexes
def annotate_test_xml(ixml, oxml, pred_path, tokens_path, spans_path):
"""Annotate the XML from CRF labels.
Args:
ixml: Input XML file.
oxml: Output XML file.
pred_path: Txt file with labels.
tokens_path: Txt file with tokens.
spans_path: Txt file with token spans.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
# Open XML test file and read it.
with codecs.open(ixml, 'r', 'utf-8') as ifile:
root = etree.parse(ifile)
# Get all Element_Sentence
Sentences = []
for review in root.getroot().iterchildren():
for sentences in review.iterchildren():
Sentences += sentences.getchildren()
i_sentences = iter(Sentences)
with codecs.open(pred_path, 'r', 'utf-8') as pfile, codecs.open(tokens_path, 'r', 'utf-8') as tfile, codecs.open(spans_path, 'r', 'utf-8') as sfile:
sentence = i_sentences.next()
opinions = etree.Element('Opinions')
sentence.append(opinions)
new_node = True
for (pred, token, span) in zip(pfile, tfile, sfile):
pred = pred.strip()
token = token.strip()
span = span.strip()
if not pred:
# Next sentence
try:
new_node = True
sentence = i_sentences.next()
opinions = etree.Element('Opinions')
sentence.append(opinions)
except StopIteration:
# No more sentence in this Review
break
else:
if pred == 'O':
new_node = True
else:
# We've got a prediction!
if new_node:
new_node = False
# New prediction
opinion = etree.Element('Opinion')
opinion.set('polarity', '')
# opinion.set('category', pred)
opinion.set('category', '')
start = span.split(' ')[0]
end = span.split(' ')[1]
opinion.set('from', start)
opinion.set('to', end)
opinion.set('target', token)
opinions.append(opinion)
else:
# A continuation
end = span.split(' ')[1]
opinion.set('to', end)
old_target = opinion.get('target')
opinion.set('target', old_target + ' ' + token)
with open(oxml, 'wb') as ofile:
ofile.write(etree.tostring(root, encoding='UTF-8',
pretty_print=True, xml_declaration=True))
def f_forms(ipath, opath):
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
for word in ifile:
word = word.strip()
if word:
# caps?
v = True in [c.isupper() for c in word]
ofile.write(str(v))
ofile.write('\t')
# all caps?
v = word.isupper()
ofile.write(str(v))
ofile.write('\t')
# Beg with caps?
v = word[0].isupper()
ofile.write(str(v))
ofile.write('\t')
# Has punc?
v = True in [c in string.punctuation for c in word]
ofile.write(str(v))
ofile.write('\t')
# all punc?
v = not (False in [c in string.punctuation for c in word])
ofile.write(str(v))
ofile.write('\t')
# has digit?
v = True in [c.isdigit() for c in word]
ofile.write(str(v))
ofile.write('\t')
# all digit?
v = word.isdigit()
ofile.write(str(v))
ofile.write('\n')
def f_word_shape(ipath, opath):
"""Add word shape features from ipath to opath.
Args:
ipath: Input file with one word per line.
opath: Output file with word shape instead of word.
Returns:
Nothing.
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
for word in ifile:
word = word.strip()
if word:
ofile.write(word_shape(word))
ofile.write('\n')
def word_shape(word, compressed=True):
"""Return the compressed shape representation of word.
See https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1764467/ for a
reference on compressed shape representation.
All capitalized letters are replaced by 'A' and non-capitalized
letters by 'a'.
All digits are replaced by '0'.
All other symbols are replaced by '_'.
Args:
word: Input word.
compressed: Whether we should compress the representation or
not.
Returns:
The compressed shape representation of word.
"""
ret = ''
if type(word) is not unicode:
word = word.decode('utf-8')
last = ''
cur = ''
for letter in word:
last = cur
if letter.isupper():
cur = 'A'
elif letter.islower():
cur = 'a'
elif letter.isdigit():
cur = '0'
else:
cur = '_'
if compressed and cur != last:
ret += cur
return ret
def f_stopwords(ipath, opath, stopwords=[]):
"""Extract stopwords information.
Args:
ipath: Inpu file with one word per line.
opath: Output file TRUE if word is a stopword.
Returns:
Nothing.
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
for word in ifile:
word = word.strip()
if word:
if word.lower() in stopwords:
ofile.write('TRUE')
else:
ofile.write('FALSE')
ofile.write('\n')
def f_senna(ipath, opath):
"""Extract POS/NER/CHK features with Senna.
Args:
ipath: Input file.
opath: Feature output file.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
import data
with open(ipath, 'rb') as ifile, open(opath, 'wb') as ofile:
p = Popen(['./senna', '-notokentags', '-usrtokens', '-pos', '-chk', '-ner'],
stdin=ifile,
stdout=ofile, stderr=PIPE, cwd=data.SENNA_PATH)
out, err = p.communicate()
if p.returncode != 0:
print(err.replace('*', '#'))
def f_senna_pos(ipath, opath):
"""Extract POS feature with Senna.
Args:
ipath: Input file.
opath: Feature output file.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
import data
with open(ipath, 'rb') as ifile, open(opath, 'wb') as ofile:
p = Popen(['./senna', '-notokentags', '-usrtokens', '-pos'],
stdin=ifile,
stdout=ofile, stderr=PIPE, cwd=data.SENNA_PATH)
out, err = p.communicate()
if p.returncode != 0:
print(err.replace('*', '#'))
def f_senna_ner(ipath, opath):
"""Extract NER feature with Senna.
Args:
ipath: Input file.
opath: Feature output file.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
import data
with open(ipath, 'rb') as ifile, open(opath, 'wb') as ofile:
p = Popen(['./senna', '-notokentags', '-usrtokens', '-ner'],
stdin=ifile,
stdout=ofile, stderr=PIPE, cwd=data.SENNA_PATH)
out, err = p.communicate()
if p.returncode != 0:
print(err.replace('*', '#'))
def f_senna_chk(ipath, opath):
"""Extract CHK feature with Senna.
Args:
ipath: Input file.
opath: Feature output file.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
import data
with open(ipath, 'rb') as ifile, open(opath, 'wb') as ofile:
p = Popen(['./senna', '-notokentags', '-usrtokens', '-chk'],
stdin=ifile,
stdout=ofile, stderr=PIPE, cwd=data.SENNA_PATH)
out, err = p.communicate()
if p.returncode != 0:
print(err.replace('*', '#'))
def f_bonsai(ipath, opath):
"""Extract POS features with BONSAI.
Args:
ipath: Input file.
opath: Feature output file.
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
import data
temp_ofile = tempfile.NamedTemporaryFile(delete=False)
with codecs.open(ipath, 'r', 'utf-8') as ifile:
p = Popen(data.bonsai_cmd,
stdin=ifile,
stdout=temp_ofile, stderr=PIPE, env=os.environ, cwd=os.environ['BONSAI'])
out, err = p.communicate()
print(err)
sys.stdout.flush()
if p.returncode != 0:
print(err.replace('*', '#'))
temp_ofile.close()
text_utils.cut(temp_ofile.name, [4], opath)
# os.remove(temp_ofile.name)
def f_treetagger(ipath, opath, tagger):
"""Extract POS and LEMME features with TreeTagger.
Args:
ipath: Input file.
opath: Feature output file.
taglang: The lang for the tagger (en, fr).
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
words = []
for word in ifile:
word = word.strip()
if word:
words.append(word)
else:
tags = tagger.tag_text('\n'.join(words), tagonly=True)
tags2 = treetaggerwrapper.make_tags(tags)
for (word, pos, lemma) in tags2:
ofile.write(pos)
ofile.write('\t')
ofile.write(lemma)
ofile.write('\n')
ofile.write('\n')
words = []
def f_treetagger_pos(ipath, opath, tagger):
"""Extract POS feature with TreeTagger.
Args:
ipath: Input file.
opath: Feature output file.
taglang: The lang for the tagger (en, fr).
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
words = []
for word in ifile:
word = word.strip()
if word:
words.append(word)
else:
tags = tagger.tag_text('\n'.join(words), tagonly=True)
tags2 = treetaggerwrapper.make_tags(tags)
for (word, pos, lemma) in tags2:
ofile.write(pos)
ofile.write('\n')
ofile.write('\n')
words = []
def f_treetagger_lemme(ipath, opath, tagger):
"""Extract LEMME feature with TreeTagger.
Args:
ipath: Input file.
opath: Feature output file.
taglang: The lang for the tagger (en, fr).
Returns:
Nothing
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
words = []
for word in ifile:
word = word.strip()
if word:
words.append(word)
else:
tags = tagger.tag_text('\n'.join(words), tagonly=True)
tags2 = treetaggerwrapper.make_tags(tags)
for (word, pos, lemma) in tags2:
ofile.write(lemma)
ofile.write('\n')
ofile.write('\n')
words = []
def chunks(l, n):
""" Yield n successive chunks from l.
http://stackoverflow.com/a/2130042
Args:
l: The list to split.
n: The number of chunks.
Returns:
Returns an iterator over the n chunks.
"""
newn = int(1.0 * len(l) / n + 0.5)
for i in xrange(0, n-1):
yield l[i*newn:i*newn+newn]
yield l[n*newn-newn:]
def split(a, n):
k, m = len(a) / n, len(a) % n
return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(n))
def split_lst(lst, splitter):
"""Split lst into the lists specified by splitter.
E.g.
>>> split_lst(range(5), [4, 1])
[[[1, 2, 3, 4], [0]],
[[2, 3, 4, 0], [1]],
[[3, 4, 0, 1], [2]],
[[4, 0, 1, 2], [3]],
[[0, 1, 2, 3], [4]]]
Args:
lst: variable documentation.
n: variable documentation.
n_train: variable documentation.
n_test: variable documentation.
Returns:
Returns information
Raises:
IOError: An error occurred.
"""
ret = []
if len(lst) != sum(splitter):
raise ValueError()
for i in range(len(lst)):
lst = rotate(lst, 1)
seg = []
acc = 0
for s in splitter:
seg.append(lst[acc:acc+s])
acc += s
ret.append(seg)
return ret
def rotate(l, n):
"""Rotate a list by n elements."""
return l[n:] + l[:n]
def merge_xml_files(files, opath):
"""Merge XML files assuming they have the same root element.
Args:
files: variable documentation.
opath: variable documentation.
Returns:
Nothing.
Raises:
IOError: An error occurred.
"""
root = None
for ipath in files:
with codecs.open(ipath, 'r', 'utf-8') as ifile:
tree = etree.parse(ifile)
if root is None:
root = tree.getroot()
else:
for child in tree.getroot().iterchildren():
root.append(child)
with open(opath, 'wb') as ofile:
ofile.write(etree.tostring(root, encoding='UTF-8',
pretty_print=True,
xml_declaration=True))
def f_lexicon(ipath, opath, lexicon, not_found=None, found=None):
"""Project lexicon on ipath.
Args:
ipath: variable documentation.
lexicon: variable documentation.
opath: variable documentation.
Returns:
Returns information
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
for word in ifile:
word = word.strip()
if word:
word = word.lower()
if word in lexicon:
if found is None:
ofile.write(lexicon[word])
else:
ofile.write(found)
else:
if not_found is None:
ofile.write(word)
else:
ofile.write(not_found)
ofile.write('\n')
def f_none(ipath, opath):
None
def f_lexicon_multi_words(ipath, opath, lexicon, splitter=lambda s: s.split(),
not_found=None, found=None):
"""Project lexicon on ipath.
Args:
ipath: variable documentation.
lexicon: variable documentation.
opath: variable documentation.
Returns:
Returns information
Raises:
IOError: An error occurred.
"""
with codecs.open(ipath, 'r', 'utf-8') as ifile:
with codecs.open(opath, 'w', 'utf-8') as ofile:
sentence = []
for word in ifile:
word = word.strip()
if word != '':
sentence.append(word.lower())
else:
t_sentence = [None] * len(sentence)
j = 0
for entry in lexicon:
t_entry = splitter(entry)
t_entry_len = len(t_entry)
if t_entry_len == 0:
continue
t_words = []
for i in range(len(sentence)):
word = sentence[i]
t_words.append(word)
if t_words == t_entry:
if found is None:
marker = lexicon[entry]
else:
marker = found
for j in range(t_entry_len):
t_sentence[i - j] = marker
t_words = []
if len(t_words) == t_entry_len:
t_words.pop(0)
idx = i - (t_entry_len - 1)
if t_sentence[idx] is None:
if not_found is None:
t_sentence[idx] = word
else:
t_sentence[idx] = 'NOT_FOUND'
for i in range(len(t_sentence)):
if t_sentence[i] is None:
if not_found is None:
t_sentence[i] = sentence[i]
else:
t_sentence[i] = 'NOT_FOUND'
ofile.write('\n'.join(t_sentence))
ofile.write('\n\n')
sentence = []
def read_bing_liu(neg_path, pos_path):
"""Return a dictionary of negative/positive words.
Args:
neg_path: variable documentation.
pos_path: variable documentation.
Returns:
A dictionary of positive and negative words.
Raises:
IOError: An error occurred.
"""
ret = {}
for (path, c) in [(neg_path, 'negative'),
(pos_path, 'positive')]:
with codecs.open(path, 'r', 'utf-8') as ifile:
for word in ifile:
word = word.strip()
if word and not word.startswith(';'):
ret[word] = c
return ret
def read_mpqa(mpqa_path):
"""Return a dictionary of negative/positive words.
Args:
neg_path: variable documentation.
pos_path: variable documentation.
Returns:
A dictionary of positive and negative words.
Raises:
IOError: An error occurred.
"""
ret = {}
with codecs.open(mpqa_path, 'r', 'utf-8') as ifile:
for line in ifile:
line = line.strip()
cols = line.split()
if len(cols) == 6:
word = '='.join(cols[2].split('=')[1:])
polarity = '='.join(cols[5].split('=')[1:])
ret[word] = polarity
return ret
def read_mpqa_plus(mpqa_path_plus):
"""Return a dictionary of negative/positive words.
Args:
Returns:
A dictionary of positive and negative words.
Raises:
IOError: An error occurred.
"""
ret = {}
with codecs.open(mpqa_path_plus, 'r', 'utf-8') as ifile:
tree = etree.parse(ifile)
root = tree.getroot()
for lexical_entry in root.iterchildren():
word = None
polarity = None
for el in lexical_entry.iterchildren():
if el.tag == 'morpho':
for node in el.iterchildren():
if node.tag == 'name':
word = node.text
if el.tag == 'evaluation':
polarity = el.get('subtype')
if word is not None and polarity is not None:
ret[word] = polarity
return ret
def read_blogoscopie(path):
"""Return a dictionary of negative/positive words.
Args:
path: Path to file.
Returns:
A dictionary of positive and negative words.
Raises:
IOError: An error occurred.
"""
ret = {}
with codecs.open(path, 'r', 'utf-8') as ifile:
for line in ifile:
line = line.strip()
data = line.split('\t')
ret[data[0]] = data[1]
return ret
def read_lidilem(lidilem_path, pol_col):
"""Return a dictionary of negative/positive words.
Format:
nom;domaine(s);sous-domaine(s);niveau de langue;intensité;polarité;fig/loc;
Args:
lidilem_path: Path to csv
pol_col: The col containing the polarity.
Returns:
A dictionary of positive and negative words.
Raises:
IOError: An error occurred.
"""
ret = {}
with codecs.open(lidilem_path, 'r', 'utf-8') as ifile:
first = True
for line in ifile:
if first:
# skip first line with headers
first = False
continue
line = line.strip()
col = line.split(';')
if col[pol_col] != '':
ret[col[0]] = col[pol_col]
return ret
def merge_pred_gold(pred_path, gold_path, opath):
"""Merge XML pred and gold XML.
Args:
pred_path: variable documentation.
gold_path: variable documentation.
opath: variable documentation.
Returns:
Nothing.
Raises:
IOError: An error occurred.
"""
with codecs.open(pred_path, 'r', 'utf-8') as ifile:
p_root = etree.parse(ifile).getroot()
with codecs.open(gold_path, 'r', 'utf-8') as ifile:
g_root = etree.parse(ifile).getroot()
for (p_review, g_review) in zip(p_root.iterchildren(),
g_root.iterchildren()):
for (p_sentences, g_sentences) in zip(p_review.iterchildren(),
g_review.iterchildren()):
for (p_sentence, g_sentence) in zip(p_sentences.iterchildren(),
g_sentences.iterchildren()):
for (p_element, g_element) in zip(p_sentence.iterchildren(),
g_sentence.iterchildren()):
if p_element.tag == 'Opinions':
for g_opinion in g_element.iterchildren():
if g_opinion.get('target') == 'NULL':
g_element.remove(g_opinion)
for p_opinion in p_element.iterchildren():
new_opinion = etree.Element('OpinionPred')
for attr in p_opinion.attrib:
new_opinion.set(attr, p_opinion.get(attr))
g_element.append(new_opinion)