/
inline_terms_legal.py
executable file
·2591 lines (2521 loc) · 121 KB
/
inline_terms_legal.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
from abbreviate import *
from filter_legal import *
from websearch import *
et_al_citation = re.compile(' et[.]? al[.]? *$')
ok_path_types = ['url'] ## currently 'ratio' is not an ok_path_type
compound_inbetween_string = re.compile('^ +(of|for) +((the|a|an|[A-Z]\.) +)?$',re.I)
term_stop_words_with_periods = re.compile('(^|\s)(u\.s|e\.g|i\.e|u\.k|c\.f|see|ser)([\.\s]|$)',re.I)
lemma_dict = {}
cluster_hash = {}
term_latin_pp_hash = {}
def derive_base_form_from_plural(word):
if word in noun_base_form_dict:
return(noun_base_form_dict[word])
elif (len(word)>3) and (word[-3:] == 'ies'):
return([word[:-3]+'y',word[:-2]])
elif len(word)>2 and (word[-2:] == 'es'):
return([word[:-1],word[:-2]])
elif len(word)>1 and (word[-1]=='s') and not(word[-2] in "suciy"):
return([word[:-1]])
else:
return(False)
def nationality_check(term_lower):
if (term_lower in pos_dict) and ('NATIONALITY' in pos_dict[term_lower]):
return(True)
def section_heading_word(word):
if (len(word)>1) and (word[-1]=='s'):
if (word in ['descriptions','claims','embodiments', 'examples','fields','inventions','priorities','applications']):
return(True)
elif word in ['description', 'summary', 'claim', 'embodiment', 'example', 'explanation', 'field', 'invention', 'introduction', 'priority', 'application(s)', 'statement', 'reference']:
return(True)
def ugly_word(word):
## words that are probably typos or other stuff we don't want
if (len(word)>3) and (word[0] in "0123456789") and word[-1].isalpha():
return(True)
elif (len(word)>1) and (word[0] in "`~!@#$%^&*-_+=<>,.?/\\"):
return(True)
elif (('=' in word) or ('>' in word)):
return(True)
elif re.search('\.su[bp]$',word):
return(True)
elif not re.search('[a-zA-Z]',word):
return(True)
elif re.search('[A-Za-z]+[0-9]+[A-Za-z]+',word):
return(True)
elif re.search('^[0-9]{1,3}[a-zA-Z]$',word):
return(True)
def topic_term_ok(word_list,pos_list,term_string):
signif_term = 0
OOV_count = 0
nominalization_count = 0
nom_length = 0
non_final_common_noun = 0
has_section_heading_word = False
alpha = False
has_lower = False
has_upper = False
has_ugly = False
if (pos_list[-1] == 'INSIDE_LATIN_PP'):
return(False,False)
if term_string == False:
return(False,False)
if len(term_string) == 1:
return(False,False)
elif (len(term_string) == 2) and (("." in term_string) or (term_string[1] in '0123456789')):
## a single initial is not a term
return(False,False)
elif term_dict_check(term_string.lower(), stat_term_dict):
## return(True,False)
signif_term = 1
elif term_stop_words_with_periods.search(term_string):
return(False,False)
if (signif_term == 0) and [pos_list[-1] == 'PLURAL'] and (pos_list[-1][-1]=='s'):
bases = derive_base_form_from_plural(word_list[-1].lower())
if bases:
for base in bases:
if nationality_check(base):
return(False,False)
if signif_term > 0:
pass
elif pos_list[-1]=='PERLOC_NAME':
return(False,False)
elif (len(word_list)==1) and (len(word_list[0])==1):
return(False,False)
for num in range(len(word_list)):
if word_list[num].isupper():
has_upper = True
elif re.search('[a-z]',word_list[num]):
## true for capcase or all lower
has_lower = True
common = False
oov = False
lower = word_list[num].lower()
ugly = False
jargon_word_count = 0
if word_list[num].isupper():
allcaps = True
else:
allcaps = False
if term_dict_check(lower,stat_term_dict):
signif_term = signif_term + 1
if (not alpha) and re.search('[a-zA-Z]',lower):
alpha = True
if lower in pos_dict:
if ('NOUN' in pos_dict[lower])and (len(lower)<8):
common = True
if 'NOUN_OOV' == pos_list[num]:
oov = True
OOV_count = 1 + OOV_count
elif lower in jargon_words:
jargon_word_count = jargon_word_count + 1
if lower in noun_base_form_dict:
base = noun_base_form_dict[lower][0]
else:
base = lower
elif ugly_word(lower):
ugly = True
has_ugly = True
elif pos_list[num] in ['NOUN','NOUN_OOV','PLURAL']:
base = lower
oov = True
OOV_count = 1 + OOV_count ## some OOV words are not classified as noun
## it does not matter for our purposes if an OOV is plural or singular here
else:
base = lower
if ugly or oov:
nom_rank = 0
elif allcaps and section_heading_word(lower):
nom_rank = 0
has_section_heading_word = True
elif pos_list[num] in ['PLURAL','AMBIG_PLURAL']:
nom_rank = nom_class(base,pos_list[num]) ## 2 (for real nom), 1 (for other nom class), 0 for no nom class
else:
nom_rank = nom_class(lower,pos_list[num])
if (nom_rank>0) or (pos_list[num]=='TECH_ADJECTIVE'):
nominalization_count = 1 + nominalization_count
elif (not oov) and (jargon_word_count == 0) and common and (num==0) or (lower in ['invention','inventions']):
non_final_common_noun = non_final_common_noun+1
if nom_rank >= 2:
## only record length if real nominalization (not other nom class)
if lower.endswith('ing'):
length = len(lower)-3
else:
length = len(lower)
if length > nom_length:
nom_length = length
if has_ugly:
return(False,False)
if signif_term>0:
return(True,OOV_count>1)
if not alpha:
return(False,False)
if has_upper and (not has_lower) and has_section_heading_word:
return(False,False)
if (OOV_count >= 1) or ((nominalization_count >=3) and (len(word_list)>=4)) or (jargon_word_count > 0):
return(True,True)
if non_final_common_noun>0:
return(False,False)
elif (nom_length>11):
return(True,OOV_count>1)
elif (len(word_list)>1) and ((nominalization_count >= 1) or (jargon_word_count >=1)):
return(True,OOV_count>1)
else:
return(False,False)
def topic_term_ok_boolean(word_list,pos_list,term_string):
value1,value2 = topic_term_ok(word_list,pos_list,term_string)
return(value1)
def get_next_word(instring,start):
## 1) don't split before paren or , unless
## one of the adjacent characters is an alphachar
## or space
##
## 2) Don't break continuous string of non-space chars
## if they contain one non-letter char
word_pattern = re.compile('\w+')
punctuation_pattern = re.compile('\S')
found = word_pattern.search(instring,start)
non_white_space = punctuation_pattern.search(instring,start)
if non_white_space and found and (non_white_space.start()<found.start()):
found = non_white_space
if found:
start = found.start()
## initialize start to first word character
end = False
extend = False
border = False
while found:
border = found.end()
if (border<(len(instring)-2)) and (instring[border]=="-") and (instring[border+1]=="("):
border = border + 1
## designed to handle the '-(' case
if (border >= len(instring)):
end = found.end()
found = False
elif instring[border]=="'":
next_word = word_pattern.search(instring,found.end())
if next_word and (border+1==next_word.start()) and (next_word.group(0) in ['s','t']):
end = next_word.end()
else:
end = found.end()
found = False
elif (instring[border]=='*'):
end = border+1
found = False
elif (instring[border]=="/"):
next_word = word_pattern.search(instring,found.end())
first_word = found.group(0)
if next_word:
second_word = next_word.group(0)
if next_word and (border+1==next_word.start()) and (len(first_word)>0) and (len(second_word)>0) and first_word.isalpha() and second_word.isalpha():
end = next_word.end()
found = next_word
else:
end = found.end()
found = False
## This will not correctly identify paths (file paths, html paths, some bio names, etc.)
elif instring[border]=="-":
## Don't split at hyphen unless both adjacent chars are alpha chars maybe done
next_word = word_pattern.search(instring,found.end())
if next_word and(border+1==next_word.start()) and (((found.group(0).isalpha() and \
((len(found.group(0))==1) or found.group(0).isalpha()))) or \
((len(next_word.group(0))>3)and ((next_word.group(0)[-2:]=="ed") or (next_word.group(0)[-3:]=='ing')))):
end = next_word.end()
found = next_word
elif next_word and (not(next_word.group(0).isalpha) or not(instring[start:end].isalpha())):
end = next_word.end()
found = next_word
else:
end=found.end()
found = False
elif ((instring[border]==',') and \
((not ((border > 0) and instring[border-1].isalpha)) or (not re.search('\s',instring[border+1])))) \
or ((instring[border]==')') and \
(border<(len(instring)-1)) and (re.search('[a-zA-Z0-9]',instring[border+1]))):
## don't split unless preceding character is alphachar and following char is whitespace
next_word = word_pattern.search(instring,found.end())
if next_word:
end = next_word.end()
found = next_word
elif (instring[border]=='(') and (border>0) and (not re.search('\s',instring[border-1])):
paren_pat = parentheses_pattern_match(instring,border,2)
### parentheses_pattern2.search(instring,border)
if paren_pat and (not re.search('\s',paren_pat.group(1))):
## require matching paren pattern
## field 1 is pre-left paren (null), field 2 is between parens, field 3 is right paren
end = paren_pat.end()
found = paren_pat
else:
end = found.end()
found = False
elif (start == found.start()) and (found.end() == start+1) and (instring[start]=='('):
paren_pat = parentheses_pattern_match(instring,start,2)
### parentheses_pattern2.search(instring,start)
if paren_pat and (not re.search('\s',paren_pat.group(1))) and (len(instring)> paren_pat.end()+1) \
and (not re.search('\s',instring[paren_pat.end()+1])):
found = paren_pat
else:
end = found.end()
found = False
else:
end = found.end()
found = False
if end:
return(instring[start:end],start,end)
else:
return(False,False,False)
def bad_splitter_pattern(pattern,piece):
if (pattern.group(0)=='.') and (pattern.start()>0):
previous_word = re.search(' ([a-zA-Z]+)[.]$',piece[:pattern.start()+1])
if previous_word and (len(previous_word.group(1))==1):
return(True)
else:
return(False)
else:
return(False)
def next_splitter_pattern(piece,start):
splitters=re.compile('\.|,|;|:| and | or | as well as | along with | in addition to |'+os.linesep,re.I)
pattern = splitters.search(piece,start)
while(pattern and bad_splitter_pattern(pattern,piece)):
start = pattern.end()
pattern = splitters.search(piece,start)
return(pattern)
def is_nom_piece(word):
lower = word.lower()
if lower in ['invention','inventions']:
return(False)
if (lower in noun_base_form_dict) and (lower[-1]=='s'):
base = noun_base_form_dict[lower][0]
else:
base = lower
nom_rank = nom_class(base,'NOUN')
if nom_rank >= 2:
return(True)
else:
return(False)
def OK_chemical(chem_string):
if len(chem_string)<=2:
return(False)
elif chem_string in abbr_to_full_dict:
return(False)
else:
cap_count = 0
elements = []
current_element = ''
has_two_char_element = False
for character in chem_string:
if character.isupper():
if current_element == '':
current_element = character
elif current_element in elements:
## elements can only occur once
return(False)
else:
elements.append(current_element)
current_element = character
elif character.islower():
if len(current_element)==1:
current_element=current_element+character
if current_element in elements:
## elements can only occur once
return(False)
elements.append(current_element)
has_two_char_element = True
current_element = ''
else:
## a lowercase letter must immediately follow an uppercase
return(False)
elif len(current_element)>0:
if current_element in elements:
## elements can only occur once
return(False)
elements.append(current_element)
current_element = ''
if current_element:
if current_element in elements:
## elements can only occur once
return(False)
elements.append(current_element)
if (len(elements)>2) or ((len(elements)==2) and \
(has_two_char_element or re.search('[0-9]',chem_string))):
return(True)
else:
return(False)
def get_next_possible_match(search_object,text,start):
space = re.compile(' ')
match = space.search(text,start)
if match:
end = match.start()
else:
end = len(text)
possible_match = search_object.search(text[:end],start)
while (not possible_match) and (end < len(text)):
start = end
if ' ' in text[start+1:]:
end = (text[start+1:].index(' '))+start+1
else:
end = len(text)
if len(text[start:end])>100:
possible_match = False
else:
possible_match = search_object.search(text[:end],start)
if possible_match:
return(start,possible_match)
else:
return(len(text),False)
def get_next_chemical_match(text,start):
chemical_formula_piece1 = '(-?((A[glmrstu])|(B[aehikr]?)|(C[adeflmorsu]?)|(D[by])|(E[rsu])|(F[emr]?)|(G[ade])|(H[efgos]?)|(I[nr]?)|(Kr?)|(L[airu])|(M[dgnot])|(N[abdeiop]?)|(Os?)|(P[abdmortu]?)|(R[abefhnu])|(S[bcegimnr]?)|(T[abcehilm])|(U)|(V)|(W)|(Xe)|(Yb?)|(Z[nr]))[0-9]?-?)'
chemical_formula_piece2 = '(-?\(((A[glmrstu])|(B[aehikr]?)|(C[adeflmorsu]?)|(D[by])|(E[rsu])|(F[emr]?)|(G[ade])|(H[efgos]?)|(I[nr]?)|(Kr?)|(L[airu])|(M[dgnot])|(N[abdeiop]?)|(Os?)|(P[abdmortu]?)|(R[abefhnu])|(S[bcegimnr]?)|(T[abcehilm])|(U)|(V)|(W)|(Xe)|(Yb?)|(Z[nr]))[0-9]?(\)[0-9]?)-?)'
chemical_piece = '('+chemical_formula_piece2+')|('+chemical_formula_piece1+')'
chemical_formula = re.compile('(^| )(('+chemical_piece+'){2,})($| )')
## group 2 is chemical
local_start = start
local_start,possible_match = get_next_possible_match(chemical_formula,text,local_start)
while possible_match:
if OK_chemical(possible_match.group(2)):
return(possible_match)
else:
local_start = possible_match.end(2)
possible_match = chemical_formula.search(text,local_start)
def OK_url(path_string):
pivot_match = re.search('(^[^/]*)([:.])([^/]*)',path_string)
if pivot_match:
if pivot_match.group(2) == ':':
return(True)
elif (len(pivot_match.group(1))>1) and (len(pivot_match.group(3))>1):
return(True)
def OK_path(path_string,url=False):
if (path_string.count('/')>1) \
and re.search('[a-zA-Z]',path_string) \
and re.search('^[ -~]*$',path_string) \
and (not re.search('^((WO)|(W/O)|(PCT))',path_string)) \
and ((not url) or OK_url(path_string)):
return(True)
def get_next_path_match(text,start):
path_chunk_string = '(([^ /;,=<>()\[\]]+)(//?([^ /;,=<>()\[\]]+)))'
path_chunk_formula_string = '('+path_chunk_string+ ' ?)+'+path_chunk_string
## there must be at least two chunks for there to be a path
## all but the last chunk can end in a space
path_chunk_formula = re.compile(path_chunk_formula_string)
## add chunk to formula if separated by space
## this may need to be filtered because it may pick up words otherwise
## well-formedness constraints include: requirement of having at
## least one number, 1 lowercase/uppercase sequence, or minimum
## length without such things
path_chunk_no_url = '(([^ /;,=<>()\[\]]+)(/([^ /;,=<>()\[\]]+)))'
path_chunk_formula_no_url_string = '('+path_chunk_no_url+ ')+'+path_chunk_no_url
path_chunk_formula2 = re.compile(path_chunk_formula_no_url_string)
current_start = start
path_match = path_chunk_formula.search(text,current_start)
path_match2 = path_chunk_formula2.search(text,current_start)
while path_match or path_match2:
if path_match and path_match2:
if (path_match.start() < path_match2.start()) or \
((path_match.start() == path_match2.start()) and \
(path_match.end() <= path_match2.end())):
if (re.search('^[^/]*:[^/]*/',path_match.group(0)) or re.search('^[^/]*[a-zA-Z]\.[a-zA-Z][^/]*/',path_match.group(0)))\
and OK_path(path_match.group(0),url=True):
return(path_match,'url')
elif (path_match.end() == path_match2.end()):
if OK_path(path_match2.group(0)):
return(path_match2,'ratio')
else:
current_start = path_match.end()
path_match = path_chunk_formula.search(text,current_start)
path_match2 = path_chunk_formula2.search(text,current_start)
else:
current_start = path_match.end()
path_match = path_chunk_formula.search(text,current_start)
elif OK_path(path_match2.group(0)):
return(path_match2,'ratio')
else:
current_start = path_match2.end()
path_match2 = path_chunk_formula2.search(text,current_start)
elif path_match:
if (re.search('^[^/]*:[^/]*/',path_match.group(0)) or re.search('^[^/]*[a-zA-Z]\.[a-zA-Z][^/]*/',path_match.group(0))) \
and OK_path(path_match.group(0),url=True):
return(path_match,'url')
else:
current_start = path_match.end()
path_match = path_chunk_formula.search(text,current_start)
elif path_match2:
if OK_path(path_match2.group(0)):
return(path_match2,'ratio')
else:
current_start = path_match2.end()
path_match2 = path_chunk_formula2.search(text,current_start)
else:
## current_start = path_match.end()
## path_match = path_chunk_formula.search(text,current_start)
print('this should be impossible -- there must be a bug')
## input()
return(False,False)
return(False,False)
def get_formulaic_term_pieces(text,offset):
start = 0
gene_sequence = re.compile('(^|[^A-Za-z0-9\'-])((-?[0-9]\'?)?(([CATG]{4,})|([CcAaTtGg]{5,}))(-?[0-9]\'?)?)(\$|[^A-Za-z0-9\'-])')
## keep group 2
path_match,path_type = get_next_path_match(text,start)
chemical_match = get_next_chemical_match(text,0)
gene_match = gene_sequence.search(text)
next_match = False
start = 0
output = []
while (path_match or chemical_match or gene_match):
minimum_new_start = False
next_match = False
match_type = False
for match,local_type in [[path_match,'path'], [chemical_match,'chemical'], [gene_match,'gene']]:
if match and ((not next_match) or (match.start() < minimum_new_start)):
minimum_new_start = match.start()
next_match = match
match_type = local_type
if next_match:
## triples should be in same/similar format as get_topic_terms3 triples: [start_offset,end_offset,string]
## but they should include a fourth item: type
## later -- we can remove conflicts between the two
if (match_type in ['gene','chemical']):
# ## group 2
start_offset = next_match.start(2)+offset
end_offset = next_match.end(2)+offset
term_string = next_match.group(2)
start = next_match.end(2)
output.append([start_offset,end_offset,term_string,False,False,match_type])
## print(term_string)
else:
start_offset = next_match.start()+offset
end_offset = next_match.end()+offset
term_string = next_match.group(0)
if match_type == 'path':
## preparing for futher elaboration of code
if path_type in ok_path_types:
output.append([start_offset,end_offset,term_string,False,False,path_type])
else:
output.append([start_offset,end_offset,term_string,False,False,match_type])
start = next_match.end()
if next_match == path_match:
path_match,path_type = get_next_path_match(text,start)
elif next_match == chemical_match:
## print('chem match',start)
chemical_match = get_next_chemical_match(text,start)
elif next_match == gene_match:
gene_match = gene_sequence.search(text,start)
output.sort()
return(output)
def merge_formulaic_and_regular_term_tuples(term_tuples,formulaic_tuples):
## initially, remove term_tuples that intersect at all with formulaic_tuples
## this might be the wrong strategy -- we need to evaluate
## also, add a fourth element to term_tuples, 'chunk-based' indicting these are obtained with a chunking procedure
## (even though some of them will be obtained some other way)
## also currently, this is being done before compound tuples or lemmas are being created
## not sure exactly of the ramifications
## ALSO: add term type to all next_term instances
output = []
## both term_tuples and formulaic_tuples are sorted (the first 2 fields are start and end offsets)
term_pointer = 0
formula_pointer = 0
if len(term_tuples)>0:
next_term = term_tuples[term_pointer]
next_term.append('chunk-based')
else:
next_term = False
if len(formulaic_tuples)> 0:
next_formula = formulaic_tuples[formula_pointer]
else:
next_formula = False
while next_term or next_formula:
if not next_term:
output.extend(formulaic_tuples[formula_pointer:])
next_formula = False
elif not next_formula:
for term in term_tuples[term_pointer:]:
if len(term)<6:
term.append('chunk-based')
output.append(term)
next_term = False
elif next_term[0] < next_formula[0]:
## 2 conditions:
## A) next term completely preceded
## then formula (keep current next term and increment)
## B) they overlap, but next_term begins first
## -- just increment next term and ignore current next term
if next_term[1] < next_formula[0]:
output.append(next_term)
term_pointer = term_pointer+1
if len(term_tuples)>term_pointer:
next_term = term_tuples[term_pointer]
next_term.append('chunk-based')
else:
next_term = False
elif next_formula[1] < next_term[0]:
## if next_formula completely precedes next_term, keep formula and increment
output.append(next_formula)
formula_pointer = formula_pointer+1
if len(formulaic_tuples)>formula_pointer:
next_formula = formulaic_tuples[formula_pointer]
else:
next_formula = False
else:
## in all other conditions there is some overlap, but getting rid of
## the next term would solve the overlap
term_pointer = term_pointer+1
if len(term_tuples)>term_pointer:
next_term = term_tuples[term_pointer]
next_term.append('chunk-based')
else:
next_term = False
return(output)
def global_formula_filter(term_list,term_hash,type_hash):
chemical_filter_pattern = re.compile('^([A-Z]*)([0-9])$')
chemical_matches = {}
for term in term_list:
if (term in type_hash) and (type_hash[term][0] == 'chemical'):
match = chemical_filter_pattern.search(term)
if match:
key = match.group(1)
value = match.group(0)
if key in chemical_matches:
if value in chemical_matches[key]:
pass
else:
chemical_matches[key].append(value)
else:
chemical_matches[key] = [value]
for key in chemical_matches:
if len(chemical_matches[key])>1:
for value in chemical_matches[key]:
term_list.remove(value)
term_hash.pop(value)
def get_topic_terms(text,offset,filter_off=False):
txt_markup = re.compile('(\[in-line-formulae\].*?\[/in-line-formulae\])|(</[a-z]+>)|(<(/)?[a-z]+( [a-z]+=[^>]+)* ?>)',re.I)
single_quote_pattern=re.compile('(\s|^)[\`\'‘](?!(s[^a-z]|d[^a-z]| |t[^a-z]|ll[^a-z]|m[^a-z]|ve[^a-z]|re[^a-z]))([^\`\']*?)[\'’](?!(s[^a-z]|d[^a-z]|t[^a-z]|ll[^a-z]|m[^a-z]|ve[^a-z]|re[^a-z]))')
## '...', where ' is not followed by a contraction or possessive marker (the first one cannot be followed by a space either,
## since this would make it a second quote or a plural possessive marker -- note this procludes an apostrophe inside a single quote
double_quote_pattern=re.compile('(\s|^)["“]([^"“”]*?)["”](\s|$)')
first_character_pattern=re.compile('[^ ,\.?><\'";:\]\[{}\-_=)(*&\^%$\#@!~]')
start = 0
paren_pat = parentheses_pattern_match(text,start,3)
### parentheses_pattern3.search(text,start)
txt_markup_match = txt_markup.search(text,start)
pieces = []
topic_terms = []
extend_antecedent = False
last_start = False
pre_np = False
## Part 1: based on get_next_abbreviation_relations
## it servers two purposes: (a) it breaks up the text by the round and square parentheses (reliable units); (b) it identifies
## abbreviations and their antecedents as terms
while (paren_pat or txt_markup_match):
if txt_markup_match and (txt_markup_match.start()>=start) and ((not paren_pat) or (paren_pat.start()>txt_markup_match.start())):
pieces.append([start,text[start:txt_markup_match.start()]])
start = txt_markup_match.end()
txt_markup_match = txt_markup.search(text,start)
elif paren_pat and (paren_pat.start()<start):
## in case parens are inside of txt_markup
### paren_pat = parentheses_pattern3.search(text,start)
paren_pat = parentheses_pattern_match(text,start,3)
elif txt_markup_match and (not paren_pat):
txt_markup_match = txt_markup.search(text,start)
else:
result = False
Fail = False
first_word_break=re.search('[ ,;:]',paren_pat.group(2))
if first_word_break:
abbreviation=paren_pat.group(2)[:first_word_break.start()]
else:
abbreviation=paren_pat.group(2)
search_end = paren_pat.start()
search_end,Fail = find_search_end(text,search_end)
if ill_formed_abbreviation_pattern(paren_pat) or re.search('^[a-zA-Z]$',abbreviation):
Fail = True
else:
previous_words = remove_empties(word_split_pattern.split(text[start:search_end].rstrip(' ')))
if Fail or (not abbreviation) or ((not abbreviation.isupper()) and (abbreviation in pos_dict)):
result = False
else:
## lowercase nouns in pos_dict are probably not really abbreviations
result = abbreviation_match(abbreviation,previous_words,text,search_end,offset,False,False)
## result is a list
if result and (result[3] == 'JARGON'):
## ARG1 is the full form
## ARG2 is the abbreviation
ARG1_start = result[0]
ARG1_end = result[1]
if result[4]:
ARG2_start = paren_pat.start(2)+offset
ARG2_end = ARG2_start+len(abbreviation)-1
if filter_off or (topic_term_ok_boolean([result[2]],['NOUN_OOV'],result[2]) and topic_term_ok_boolean([abbreviation[1:]],'NOUN_OOV',abbreviation[1:])):
topic_terms.extend([[ARG1_start,ARG1_end,result[2],False,'ABBREVIATION'],[ARG2_start,ARG2_end,abbreviation[1:],False,'ABBREVIATION']])
else:
ARG2_start = paren_pat.start(2)+offset
ARG2_end = ARG2_start+len(abbreviation)
if filter_off or (topic_term_ok_boolean([result[2]],['NOUN_OOV'],result[2]) and topic_term_ok_boolean([abbreviation],'NOUN_OOV',abbreviation)):
topic_terms.extend([[ARG1_start,ARG1_end,result[2],False,'ABBREVIATION'],[ARG2_start,ARG2_end,abbreviation,False,'ABBREVIATION']])
pieces.append([start,text[start:paren_pat.start()]])
if txt_markup_match and (txt_markup_match.start()>start) and (txt_markup_match.end()<paren_pat.end()):
start = txt_markup_match.start()
else:
start = paren_pat.end()
elif txt_markup_match and (txt_markup_match.start()>start) and (txt_markup_match.end()<paren_pat.end()):
start = txt_markup_match.start()
else:
pieces.extend([[start,text[start:paren_pat.start()]],[paren_pat.start(2),paren_pat.group(2)]])
start = paren_pat.end()
### paren_pat = parentheses_pattern3.search(text,paren_pat.end())
paren_pat = parentheses_pattern_match(text,paren_pat.end(),3)
if start and (len(text) > start):
pieces.append([start,text[start:]])
if len(pieces)==0:
pieces=[[0,text]]
pieces2 = []
## Part 2: quotation mark off reliable units, separate these out
for meta_start,piece in pieces:
start = 0
sing = single_quote_pattern.search(piece,start)
doub = double_quote_pattern.search(piece,start)
while (start < len(piece)) and (sing or doub):
if doub and ((not sing) or ((sing.start() < doub.start()) and (sing.end()>doub.end()))):
## if doub nested inside of singular, assume singular quotes are in error
pieces2.extend([[meta_start+start,piece[start:doub.start()]],\
[meta_start+doub.start(2),doub.group(2)]])
start = doub.end()
doub = double_quote_pattern.search(piece,start)
if sing:
sing = single_quote_pattern.search(piece,start)
elif (not doub) or (sing.end() < doub.start()):
## if there is no doub or if sing completely precedes doub
pieces2.extend([[meta_start+start,piece[start:sing.start()]],\
[meta_start+sing.start(3),sing.group(3)]])
start = sing.end()
sing = single_quote_pattern.search(piece,start)
elif (sing.start()>doub.start()) and (sing.end() < doub.end()):
## nesting sing inside doub
pieces2.extend([[meta_start+start,piece[start:doub.start()]],\
[meta_start+doub.start(),piece[doub.start():sing.start()]],\
[meta_start+sing.start(3),sing.group(3)],\
[meta_start+sing.end(),piece[sing.end():doub.end()]]])
start = doub.end()
doub = double_quote_pattern.search(piece,start)
elif doub.end() < sing.start():
## doub first -- do doub only (treat similarly to first case, except don't reinitialize singular)
pieces2.extend([[meta_start+start,piece[start:doub.start()]],\
[meta_start+doub.start(2),doub.group(2)]])
start = doub.end()
doub = double_quote_pattern.search(piece,start)
## otherwise it is some sort of error
elif doub and sing:
if doub.start()<sing.start():
start = doub.start()+1
doub = double_quote_pattern.search(piece,start)
else:
start = sing.start(1)+1
sing = single_quote_pattern.search(piece,start)
elif doub:
start = doub.start()+1
doub = double_quote_pattern.search(piece,start)
elif sing:
start = sing.start(1)+1
sing = single_quote_pattern.search(piece,start)
else:
print('Error in program regarding single and double quotes')
print('piece:',piece)
print('text:',text)
## this is probably not a real instance of quotation
if start < len(piece):
pieces2.append([meta_start+start,piece[start:]])
## Part III: split into chunks by commas and abbreviations
## each resulting piece an then be analyzed syntactically based on word class
for meta_start,piece in pieces2:
## parse each piece separately
## current_out_list = []
## need a new version of splitters that provides offsets
start = 0
split_position = next_splitter_pattern(piece,start)
if not split_position:
last = True
else:
last = False
current_latin_pp_struct = False
latin_pp = False
latin_pp_start = False
while split_position or last:
start_match = first_character_pattern.search(piece,start)
if start_match:
start = start_match.start()
if last:
piece2 = piece[start:]
else:
piece2 = piece[start:split_position.start()]
current_out_list = []
current_pos_list = []
latin_pp = False
pre_np = False
first_piece = True
last_pos = False
piece3, next_word_start,next_word_end = get_next_word(piece2,0)
if piece3:
piece2_start = next_word_start
term_start = piece2_start+start ## start is the start for one level up
while piece3:
if piece3.istitle():
is_capital = True
else:
is_capital = False
lower = piece3.lower()
word_offset = next_word_start + start + meta_start + offset
if piece3 == '':
pass
else:
pos = guess_pos(lower,is_capital,offset=word_offset)
if current_latin_pp_struct:
if lower in latin_pp_dict:
## if there are two latin_pps in a row
## the first is not part of a term (we assume)
## this restarts the latin_pp buffer
current_latin_pp_struct = {'words': [lower],'dict_entry':latin_pp_dict[lower],'start':next_word_start+start}
elif lower in current_latin_pp_struct['dict_entry']:
current_latin_pp_struct['words'].append(lower)
current_latin_pp_struct['dict_entry']= \
current_latin_pp_struct['dict_entry'][lower]
pos = 'INSIDE_LATIN_PP'
elif '*NONE*' in current_latin_pp_struct['dict_entry']:
## a PP has been fully matched, ending with
## the preceding word
pp_length = len(current_latin_pp_struct['words'])
latin_pp = ' '.join(current_latin_pp_struct['words'])
current_out_list = [latin_pp]
current_pos_list = ['TECH_ADJECTIVE']
## term_start = min(term_start,current_latin_pp_struct['start'])
term_start = current_latin_pp_struct['start']
current_latin_pp_struct = False
## if completed structure,
## make one big tech_adjective
elif lower in latin_pp_dict:
current_latin_pp_struct = {'words': [lower],'dict_entry':latin_pp_dict[lower],'start':next_word_start+start}
if (pos == 'SKIPABLE_ADJ') and is_capital:
pos = 'ADJECTIVE'
if (pos in ['SKIPABLE_ADJ']) and not(current_out_list):
pass
# elif current_latin_pp_struct and not latin_pp:
# pass
elif pos in ['DET','PREP']:
pre_np = True
if current_out_list:
term_string = interior_white_space_trim(piece2[term_start-start:piece2_start])
else:
term_string = False
if (term_string == False) or (term_string == ''):
pass
elif current_out_list and (filter_off or topic_term_ok_boolean(current_out_list,current_pos_list,term_string)):
start_offset = term_start + meta_start+offset
end_offset = piece2_start+start+meta_start+offset
topic_terms.append([start_offset,end_offset,term_string,latin_pp,current_pos_list])
current_out_list = []
current_pos_list = []
latin_pp = False
elif pos in ['AMBIG_POSSESS','POSSESS']:
if piece3.endswith("'s"):
piece3 = piece3[:-2]
end_minus = 2
else:
end_minus = 0
if current_out_list:
current_out_list.append(piece3)
current_pos_list.append(pos)
else:
current_out_list = [piece3]
current_pos_list = [pos]
term_start = piece2_start + start
if current_out_list:
term_string = interior_white_space_trim(piece2[term_start-start:next_word_end-end_minus])
else:
term_string = False
if filter_off or topic_term_ok_boolean(current_out_list,current_pos_list,term_string):
start_offset = term_start + meta_start+offset
end_offset = next_word_end+start+meta_start+offset-end_minus
topic_terms.append([start_offset,end_offset,term_string,latin_pp,current_pos_list])
current_out_list = []
current_pos_list = []
latin_pp = False
pre_np = False
first_piece=False
elif (len(piece3)==1) and piece3.isalpha() and (len(piece2)>next_word_start+1) \
and (piece2[next_word_end]=='.'):
## reset next_word_end and piece3
next_word_end = next_word_end+1
piece3 = piece2[next_word_start:next_word_end]
pos = 'NOUN' ## initial can be part of term, but not term by itself
if current_out_list:
current_out_list.append(piece3)
current_pos_list.append(pos)
else:
current_out_list = [piece3]
current_pos_list = [pos]
term_start = next_word_start + start
pre_np = False
first_piece = False
elif (pos == 'ROMAN_NUMBER') and current_out_list and (len(current_out_list)>=1) and \
(current_pos_list[-1] in ['NOUN_OOV','NOUN','AMBIG_NOUN','PLURAL','AMBIG_PLURAL']):
if current_out_list:
term_string = interior_white_space_trim(piece2[term_start-start:next_word_end])
else:
term_string = False
if filter_off or topic_term_ok_boolean(current_out_list,current_pos_list,term_string):
## Roman Numerals can tack on to other terms
current_out_list.append(piece3)
current_pos_list.append(pos)
start_offset = term_start + meta_start+offset
end_offset = next_word_end+start+meta_start+offset
topic_terms.append([start_offset,end_offset,term_string,latin_pp,current_pos_list])
current_out_list = []
current_pos_list = []
latin_pp = False
pre_np = False
first_piece=False
elif (pos in ['PLURAL','AMBIG_PLURAL']) or (current_out_list and (len(current_out_list)>=1) and \
((current_pos_list[-1] == 'ADJECTIVE') and \
(pos == 'VERB') and (len(piece3)>3) and \
(piece3[-3:]=='ing'))):
## a) plural nouns must end noun groups
## b) ing verbs can sometimes also end noun groups
## c) AMBIG_PLURALS, AMBIG_SINGULARs and ing verbs cannot stand by themselves and
## they can not be initial in noun groups
## d) there is an exception -- if the next word is a nominalization,
## then the NP could continue
look_ahead,look_ahead_start,look_ahead_end = get_next_word(piece2,next_word_end)
if look_ahead:
look_ahead2,look_ahead2_start,dummy2 = get_next_word(piece2,look_ahead_end)
look_ahead2_offset = look_ahead2_start + start + meta_start + offset
if look_ahead2 and (guess_pos(look_ahead2,False,offset=look_ahead2_offset) in ['PLURAL','AMBIG_PLURAL','NOUN','AMBIG_NOUN','NOUN_OOV']):
look_ahead = False
look_ahead2 = False
if current_out_list:
current_out_list.append(piece3)
current_pos_list.append(pos)
else:
current_out_list = [piece3]
current_pos_list = [pos]
term_start = next_word_start + start
if look_ahead and is_nom_piece(look_ahead):
pass
else:
if current_out_list:
term_string = interior_white_space_trim(piece2[term_start-start:next_word_end])
else:
term_string = False
if filter_off or topic_term_ok_boolean(current_out_list,current_pos_list,term_string):
start_offset = term_start + meta_start+offset
end_offset = next_word_end+start+meta_start+offset
topic_terms.append([start_offset,end_offset,term_string,latin_pp,current_pos_list])
current_out_list = []
current_pos_list = []
latin_pp = False
else:
current_out_list = []
current_pos_list = []
latin_pp = False
pre_np = False
first_piece=False
elif pos in ['NOUN','POSSESS_OOV','AMBIG_NOUN','PERLOC_NAME','NOUN_OOV']:
## out of vocab possessive
## evaluate piece by POS
## looking for sequences of pieces that either:
## a) are unambigous nouns; or b) are OOV words
if piece3.endswith("'s"):
piece3a = piece3[:-2]
piece3b = piece3[-2:]
if current_out_list:
current_out_list.append(piece3a)
current_pos_list.append(pos)
else:
current_out_list = [piece3]
current_pos_list = [pos]
term_start = next_word_start + start
term_string = interior_white_space_trim(piece2[term_start-start:next_word_end-2])
if filter_off or topic_term_ok_boolean(current_out_list,current_pos_list,term_string):
start_offset = term_start + meta_start+offset
end_offset = next_word_end+start+meta_start+offset
topic_terms.append([start_offset,end_offset,term_string,latin_pp,current_pos_list])
current_out_list = []
current_pos_list = []
latin_pp = False
else:
current_out_list = []
current_pos_list = []
latin_pp = False
pre_np = True
first_piece=False
elif current_out_list:
current_out_list.append(piece3)
current_pos_list.append(pos)
pre_np = False
first_piece=False
else:
current_out_list = [piece3]
current_pos_list = [pos]
term_start = next_word_start + start
pre_np = False
first_piece=False
elif current_out_list and (last_pos == 'NOUN_OOV') and \
((not piece3 in signal_set) or is_capital) and \
((pos in ['TECH_ADJECTIVE','NATIONALITY_ADJ']) or ((pos == 'ADJECTIVE') and (is_capital or (term_dict_check(piece3,stat_adj_dict))))):
current_out_list.append(piece3)
current_pos_list.append(pos)
elif (current_out_list == False) and \
((not piece3 in signal_set) or is_capital) and \
((pos in ['TECH_ADJECTIVE','NATIONALITY_ADJ']) or \
((pos in ['VERB','AMBIG_VERB']) and (lower.endswith('ed') or lower.endswith('ing'))) or \
((pos == 'ADJECTIVE') and (is_capital or term_dict_check(piece3,stat_adj_dict)))):
current_out_list = [piece3]
current_pos_list = [pos]
latin_pp = False
term_start = next_word_start + start
pre_np = False
first_piece=False