-
Notifications
You must be signed in to change notification settings - Fork 0
/
flexiterm.py
2048 lines (1413 loc) · 61.9 KB
/
flexiterm.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
# # --- FlexiTerm: multi-word term recognition
# --- dependencies ---
import csv
import jellyfish
import json
import math
import numpy as np
import os
import pprint
import random
import re
import spacy
import sqlite3
import sys
import time
from nltk.stem.porter import PorterStemmer
from pathlib import Path
from spacy.matcher import PhraseMatcher
from spacy import displacy
# # --- setting up
# --- database connection ---
schema = "./config/schema.sql" # --- read database schema
try:
with open(Path(schema),'r') as file:
sql_script = file.read()
file.close()
print(sql_script[0:100] + '...') # --- preview schema
except:
print("ERROR: Schema file " + schema + " not found. Unable to create the tables.\n")
quit()
# --- database connection
con = sqlite3.connect('flexiterm.sqlite')
# --- cursor (statement) objects to execute SQL queries
cur1 = con.cursor()
cur2 = con.cursor()
cur3 = con.cursor()
# --- create database tables
cur1.executescript(sql_script)
con.commit()
# --- default settings ---
default = {
"pattern" : "(((((NN|JJ) )*NN) IN (((NN|JJ) )*NN))|((NN|JJ )*NN POS (NN|JJ )*NN))|(((NN|JJ) )+NN( CD)?)",
"stoplist" : "./config/stoplist.txt",
"Smin" : 0.962,
"Amin" : 5,
"Fmin" : 2,
"Cmin" : 1,
"acronyms" : "explicit"
}
# --- load settings ---
settings_file = "./config/settings.json"
try:
with open(Path(settings_file),"r") as file:
settings = json.load(file)
file.close()
if "pattern" in settings:
pattern = settings["pattern"]
try: re.compile(pattern)
except re.error:
print("WARNING: Invalid POS pattern: " + pattern)
print(" Using the default instead.\n")
pattern = default["pattern"]
if "stoplist" in settings:
stoplist = settings["stoplist"]
if not os.path.isfile(stoplist):
print("WARNING: Stoplist file " + stoplist + " not found.")
print(" Using the default instead.\n")
stoplist = default["stoplist"]
if "Smin" in settings:
Smin = settings["Smin"]
if not (0 < Smin and Smin < 1):
print("WARNING: Invalid token similarity threshold:", Smin);
print(" Using the default instead.\n")
Smin = default["Smin"]
if "Amin" in settings:
Amin = settings["Amin"]
if type(Amin) != int:
print("WARNING: Invalid acronym frequency threshold:", Amin);
print(" Using the default instead.\n")
Amin = default["Amin"]
if "Fmin" in settings:
Fmin = settings["Fmin"]
if type(Fmin) != int:
print("WARNING: Invalid term frequency threshold:", Fmin);
print(" Using the default instead.\n")
Fmin = default["Fmin"]
if "Cmin" in settings:
Cmin = settings["Cmin"]
if Cmin < 0.7:
print("WARNING: Invalid token C-value threshold:", Cmin);
print(" Using the default instead.\n")
Cmin = default["Cmin"]
if "acronyms" in settings:
acronyms = settings["acronyms"]
if acronyms not in ["explicit", "implicit"]:
print("WARNING: Invalid acronyms value:", acronyms);
print(" Using the default instead.\n")
acronyms = default["acronyms"]
except:
print("WARNING: Settings file " + settings_file + " not found. Using the default values instead.\n")
pattern = default["pattern"]
stoplist = default["stoplist"]
Smin = default["Smin"]
Amin = default["Amin"]
Fmin = default["Fmin"]
Cmin = default["Cmin"]
acronyms = default["acronyms"]
print("--- Settings ---")
print("* pattern :", pattern)
print("* stoplist :", stoplist)
print("* Smin :", Smin)
print("* Amin :", Amin)
print("* Fmin :", Fmin)
print("* Cmin :", Cmin)
print("* acronyms :", acronyms)
print("----------------")
# --- load stoplist ---
print("Loading stoplist from " + stoplist + "...");
try:
# --- read a CSV file
table = open(Path(stoplist),'r')
rows = csv.reader(table)
# --- insert rows from the CSV file
cur1.executemany("INSERT INTO stopword (word) VALUES (?);", rows)
con.commit()
table.close()
except sqlite3.Error as error: print(error)
file = open(Path(stoplist), 'r')
stopwords = file.read().split('\n')
file.close()
# --- load language model from spacy ---
nlp = spacy.load('en_core_web_sm')
sentencizer = nlp.add_pipe('sentencizer')
# --- delete previous output files if any
folder = "./out"
filename = ["annotations.json",
"concordances.html",
"corpus.html",
"terminology.html",
"terminology.csv"]
for name in filename:
file_path = os.path.join(folder, name)
if os.path.exists(file_path): os.remove(file_path)
# # --- load & preprocess input documents
start_time = time.perf_counter()
timer = []
# --- fix potential tagging issues
def pretagging(txt):
unit = ["meter",
"metre",
"mile",
"centi",
"milli",
"kilo",
"gram",
"sec",
"min",
"hour",
"hr",
"day",
"week",
"month",
"year",
"liter",
"litre"]
abbr = ["m",
"cm",
"mm",
"kg",
"g",
"mg",
"s",
"h",
"am",
"pm",
"l",
"ml"]
# --- insert white space in front of a unit where necessary
for u in unit:
txt = re.sub("(\d)" + u, "\\1 " + u, txt)
for a in abbr:
txt = re.sub("(\d)" + a, "\\1 " + a, txt)
# --- compress repetative punctuation into a single character
txt = re.sub("\\!+", "!", txt)
txt = re.sub("\\?+", "?", txt)
txt = re.sub("\\.+", ".", txt)
txt = re.sub("\\-+", "-", txt)
txt = re.sub("_+", "_", txt)
txt = re.sub("~+", "~", txt)
txt = re.sub("kappaB", "kappa B", txt)
txt = re.sub('([a-z0-9])/([a-z0-9])', '\\1 / \\2', txt, flags=re.IGNORECASE)
txt = re.sub("\(", " ( ", txt, flags=re.IGNORECASE)
txt = re.sub("\)", " ) ", txt, flags=re.IGNORECASE)
# --- remove long gene sequences
txt = re.sub("[ACGT ]{6,}", "", txt);
# --- normalise white spaces
txt = re.sub("\\s+", " ", txt)
# --- normalise non-ASCII characters
# ???: test with unicode characters
#txt = Normalizer.normalize(txt, Normalizer.Form.NFD);
#txt = txt.replaceAll("[^\\x00-\\x7F]", "");
return txt
# --- remove a hyphen between 2 letters so that it does not mess up the tokenisation in spacy: -/HYPH
# --- NOTE: not part of pretagging, because the hyphen is only ignored, not removed
def hyphen(txt):
txt = re.sub('([a-z])\\-([a-z])', '\\1 \\2', txt, flags=re.IGNORECASE)
# --- repeat for overlapping matches, as only one gets replaced,
# e.g. glutathione-S-transferase -> glutathione S-transferase -> glutathione S transferase
txt = re.sub('([a-z])\\-([a-z])', '\\1 \\2', txt, flags=re.IGNORECASE)
return txt
# --- generalise tags to simplify patterns (regex) specified in the settings
def gtag(tag):
if (len(tag) <= 1): tag = "PUN"
elif (tag == "PRP$"): tag = "PRP"
elif (tag == "WP$"): tag = "WP"
elif (tag.find("JJ") == 0): tag = "JJ"
elif (tag.find("NN") == 0): tag = "NN";
elif (tag.find("RB") == 0): tag = "RB";
elif (tag.find("VB") == 0): tag = "VB";
return tag
# --- prepare lemma for stemming
def prestem(lemma):
if len(lemma) > 1:
if lemma[0:1] == '-': lemma = lemma[1:] # --- strip of hyphen at the start
if len(lemma) > 1:
if lemma[-1:] == '-': lemma = lemma[:-1] # --- strip of hyphen at the end
lemma = re.sub('isation', 'ization', lemma) # --- American spelling for consistent stemming
return lemma
# --- load data
#####
cur1.execute("DELETE FROM data_document;")
cur1.execute("DELETE FROM data_sentence;")
cur1.execute("DELETE FROM data_token;")
#####
stemmer = PorterStemmer()
# --- read documents from the "text" folder
folder = "./text"
print("Loading data from " + folder + "...");
n = 0
for doc_id in os.listdir(folder):
n += 1
file_path = os.path.join(folder, doc_id)
if os.path.isfile(file_path):
print('.', end='')
file = open(file_path, "r", encoding="utf8")
verbatim = file.read()
file.close()
content = pretagging(verbatim)
row = (doc_id, content, verbatim)
cur1.execute("INSERT INTO data_document(id, document, verbatim) VALUES(?, ?, ?);", row)
# --- split sentences
s = 0
doc = nlp(hyphen(content))
for sent in doc.sents: # --- store sentences
s+=1
sentence = sent.text
tokens = " ".join([token.text for token in sent])
for token in sent:
token.tag_ = gtag(token.tag_) # --- generalise tag, e.g. JJR --> JJ
# --- prevent tagging of symbols and abbreviations as NNs
if token.text == '%': token.tag_ = 'SYM'
elif token.text.lower() in ('et', 'al', 'etc'): token.tag_ = 'XX'
elif token.text.lower() in ('related', 'based'): token.tag_ = 'JJ'
tags = " ".join([token.tag_ for token in sent])
tagged_sentence = " ".join([token.text+"/"+token.tag_ for token in sent])
sentence_id = doc_id+"."+str(s)
row = (sentence_id, doc_id, s, sentence, tagged_sentence, tags)
cur1.execute("INSERT INTO data_sentence(id, doc_id, position, sentence, tagged_sentence, tags) VALUES(?, ?, ?, ?, ?, ?)", row)
# --- tokenise sentences
p = 0
for token in sent: # --- store tokens
p+=1
lemma = token.lemma_.lower() # --- lemmatise
lemma = prestem(lemma) # --- prepare lemma for stemming
stem = stemmer.stem(lemma) # --- stem lemma
row = (sentence_id, p, token.text, stem, lemma, token.tag_)
cur1.execute("INSERT INTO data_token(sentence_id, position, token, stem, lemma, gtag) VALUES(?, ?, ?, ?, ?, ?)", row)
if n == 0:
con.close()
sys.exit('No input data found. Check the text folder.')
con.commit()
print('\nData loaded.')
cur1.execute("CREATE INDEX idx01 ON data_document(id);")
cur1.execute("CREATE INDEX idx02 ON data_token(sentence_id, position);")
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Data loaded in {run_time:0.4f} seconds")
timer.append(run_time)
# # --- extract term candidates
start_time = end_time
# --- extract NPs of a predefined structure (the pattern in the settings)
#####
cur1.execute("DELETE FROM term_phrase;")
#####
print("Extracting term candidates...");
regex = re.compile(pattern)
cur1.execute("SELECT id, tags FROM data_sentence WHERE length(sentence) > 30;") # --- extract POS tags
rows1 = cur1.fetchall()
total = len(rows1)
n = 0
for row1 in rows1:
# --- progress bar
n += 1
sys.stdout.write('\r')
p = int(100*n/total)
sys.stdout.write("[%-100s] %d%%" % ('='*p, p))
sys.stdout.flush()
sentence_id = row1[0]
tags = row1[1]
# --- match patterns
for chunk in re.finditer(regex, tags):
start = tags[:chunk.span()[0]].count(' ')+1
length = tags[chunk.span()[0]:chunk.span()[1]].count(' ')+1
# --- extract the corresponding tokens
cur2.execute("""SELECT token
FROM data_token
WHERE sentence_id = ?
AND position >= ?
AND position < ?
ORDER BY position ASC;""", (sentence_id, start, start+length))
rows2 = cur2.fetchall()
# --- trim leading stopwords
tokens = []
for row2 in rows2: tokens.append(row2[0])
i = 0
while length > 1:
if tokens[i].lower() in stopwords:
start += 1
length -= 1
i+=1
else: break
tokens = tokens[i:]
# --- trim trailing stopwords
i = len(tokens) - 1
while length > 1:
if tokens[i].lower() in stopwords:
length -= 1
i-=1
else: break
tokens = tokens[:i+1]
# --- join tokens into a phrase
phrase = " ".join(tokens)
phrase_id = sentence_id+"."+str(start)
# --- if still multi-word phrase and not too long
if 1 < length and length < 8:
# --- strip off possible . at the end
if phrase.endswith('.'): phrase = phrase[:-1]
# --- ignore phrases that contain web concepts: email address, URL, #hashtag
if not(phrase.find("@")>=0 or
phrase.find("#")>=0 or
phrase.lower().find("http")>=0 or
phrase.lower().find("www")>=0):
# --- normalise phrase by stemming
cur2.execute("""SELECT DISTINCT stem
FROM data_token
WHERE sentence_id = ?
AND ? <= position AND position < ?
EXCEPT SELECT word FROM stopword
ORDER BY stem ASC;""", (sentence_id, start, start+length))
###AND NOT (LOWER(token) = token AND LENGTH(token) < 3)
rows2 = cur2.fetchall()
stems = []
for row2 in rows2: stems.append(row2[0])
normalised = " ".join(stems)
normalised = normalised.replace('.', '') # --- e.g. U.K., Dr., St. -> UK, Dr, St
# --- store phrase as a MWT candidate
cur2.execute("""INSERT INTO term_phrase(id, sentence_id, token_start, token_length, phrase, normalised)
VALUES (?,?,?,?,?,?);""", (phrase_id, sentence_id, start, length, phrase, normalised))
cur1.execute("UPDATE term_phrase SET flat = LOWER(REPLACE(phrase, ' ', ''));")
con.commit()
cur1.execute("CREATE INDEX idx03 ON term_phrase(flat);")
cur1.execute("CREATE INDEX idx04 ON term_phrase(LOWER(phrase));")
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Term candidates extracted in {run_time:0.4f} seconds")
timer.append(run_time)
start_time = end_time
# --- re-normalise term candidates that have different TOKENISATION,
# e.g. posterolateral corner B vs. postero lateral corner
# --- keep the one with MORE tokens (e.g. postero lateral corner)
cur1.execute("DELETE FROM tmp_normalised;")
cur1.execute("""INSERT INTO tmp_normalised(changeto, changefrom)
SELECT P1.normalised, P2.normalised
FROM term_phrase P1, term_phrase P2
WHERE P1.flat = P2.flat
AND P1.token_length > P2.token_length
AND P1.normalised <> P2.normalised;""")
cur1.execute("""SELECT DISTINCT changefrom, changeto FROM tmp_normalised;""")
rows1 = cur1.fetchall()
for row1 in rows1:
changefrom = row1[0]
changeto = row1[1]
print(changefrom, "-->", changeto)
cur2.execute("UPDATE term_phrase SET normalised = ? WHERE normalised = ?;", (changeto, changefrom))
con.commit()
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Term candidates normalised in {run_time:0.4f} seconds")
timer.append(run_time)
# # --- acronym recognition method
start_time = end_time
# --- assumption: acronyms are explicitly defined in text, e.g.
# ... blah blah retinoic acid receptor (RAR) blah blah ...
# ~~~~~~~~~~~~~~~~~~~~~~ ~~~
# --- based on this paper:
# Schwartz A & Hearst M (2003)
# A simple algorithm for identifying abbreviation definitions in biomedical text,
# Pacific Symposium on Biocomputing 8:451-462 [http://biotext.berkeley.edu/software.html]
# --- alpha -> a: helps properly estimate the acronym length and simplifies matching against the long form
def pad(string):
return " " + string + " "
def greek2english(string):
letters = ["alpha", "beta", "gamma", "delta", "epsilon", "zata", "eta", "theta", "iota","kappa", "lambda", "mu", "nu", "xi", "omikron", "pi", "rho", "sigma", "tau", "upsilon", "phi","chi", "psi", "omega"]
string = pad(string)
for letter in letters:
string = re.sub(pad(letter), pad(letter[0:1]), string, flags=re.IGNORECASE)
return string.strip()
# --- checks if a string looks like an acronym
def isValidShortForm(string):
string = greek2english(string)
if len(string) < 2: # --- acronym too short
return False
elif len(string) > 8: # --- acronym too long
return False
elif not(any(char.isupper() for char in string)): # --- no uppercase
return False
elif (sum([int(c.islower()) for c in string]) > sum([int(c.isupper()) for c in string])): # --- more lowercase than uppercase
return False
elif not(string[0].isalpha() or string[0].isdigit() or string[0] == '('): # --- invalid first character
return False
elif (len(re.sub('[a-z0-9\s\'/\-]', '', string.lower())) > 0): # --- invalid characters present
return False
elif string[1] == "'": # --- 2nd character ' as in A'
return False
return True
# --- processes the context (i.e. definition) to extract the best long form for a given acronym
def bestLongForm(acronym, definition):
# --- case-insensitive matching
acronym = acronym.replace("-", "").lower()
definition = definition.lower()
d = len(definition) - 1
# --- go through the acronym & definition character by character,
# FROM RIGHT TO LEFT looking for a match
for a in range(len(acronym) - 1, -1, -1):
c = acronym[a]
if (c.isalpha() or c.isdigit()): # --- match an alphanumeric character
while ((d >= 0 and definition[d] != c) or (a == 0 and d > 0 and (definition[d-1].isalpha() or definition[d-1].isdigit()))):
d -= 1 # --- keep moving to the left
if (d < 0): # --- match failed
return None
else: # --- match found
d -= 1 # --- skip the matching character and then continue matching
d = definition.rfind(' ', 0, d+1) + 1 # --- complete the left-most word (up to the white space)
definition = definition[d:].strip() # --- delete the surplus text on the left
if definition.startswith('an '): definition = definition[3:] # --- starts with a determiner?
elif definition.startswith('a '): definition = definition[2:]
elif definition.startswith('the '): definition = definition[4:]
elif (definition.startswith('[') and definition.endswith(']')): # --- [definition]
definition = definition[1:-1]
elif (definition.startswith("'") and definition.endswith("'")): # --- 'definition'
definition = definition[1:-1]
return definition
# --- extracts all potential (acronym, definition) pairs from a given sentence
def extractPairs(sentence):
pairs = []
# --- remove double quotes
sentence = sentence.replace('"', ' ')
# --- normalise white spaces
sentence = re.sub('\s+', ' ', sentence)
acronym = ''
definition = ''
o = sentence.find(' (') # --- find (
c = -1 # --- ) index
tmp = -1
while (1 == 1):
if (o > -1):
o +=1 # --- skip white space, i.e. ' (' -> '('
c = sentence.find(')', o) # --- find closed parenthesis
# --- extract candidates for (acronym, definition)
if (c > -1):
# --- find the start of the previous clause based on punctuation
cutoff = max(sentence.rfind('. ', 0, o), sentence.rfind(', ', 0, o))
if (cutoff == -1): cutoff = -2
definition = sentence[cutoff + 2:o].strip()
acronym = sentence[o + 1:c].strip()
if (len(acronym) > 0 or len(definition) > 0): # --- candidates successfully instantiated above
if (len(acronym) > 1 and len(definition) > 1):
# --- look for parentheses nested within the candidate acronym
nextc = sentence.find(')', c + 1)
if (acronym.find('(') > -1 and nextc > -1):
acronym = sentence[o + 1:nextc]
c = nextc
# --- if separator found within parentheses, then trim everything after it
tmp = acronym.find(', ')
if (tmp > -1): acronym = acronym[0:tmp]
tmp = acronym.find('; ')
if (tmp > -1): acronym = acronym[0:tmp]
tmp = acronym.find(' or ')
if (tmp > -1): acronym = acronym[0:tmp]
if (tmp > -1): acronym = acronym[0:tmp]
# --- (or ...) -> (...)
tmp = acronym.find('or ')
if (tmp == 0): acronym = acronym[3:]
tokens = acronym.split()
if (len(tokens) > 3 or len(acronym) > len(definition)):
# --- definition found within (...)
# --- extract the last token before "(" as a candidate for acronym
tmp = sentence.rfind(' ', 0, o - 2)
substr = sentence[tmp + 1:o - 1]
# --- swap acronym & definition
definition = acronym
acronym = substr
# --- validate (... definition ...)
if (len(definition.replace('-', ' ').split(' ')) > len(acronym) + 2):
acronym = '' # --- delete acronym
acronym = acronym.strip()
definition = definition.strip()
if (isValidShortForm(acronym)):
blf = matchPair(acronym, definition)
if blf != None:
# --- NOTE: blf is already in lowercase
pairs.append([acronym, blf])
# --- prepare to process the rest of the sentence after ")"
sentence = sentence[c + 1:]
elif (o > -1): sentence = sentence[o + 1:] # --- process the rest of the sentence
acronym = ''
definition = ''
o = sentence.find(' (')
if o < 0: return pairs
# --- finds the best match for an acronym and checks if it looks like a valid long form
def matchPair(acronym, definition):
# --- abort if acronym too short
if (len(acronym) < 2): return None
# --- find the long form
blf = bestLongForm(acronym, definition)
# --- abort if no long form found
if (blf == None): return None
# --- t = the number of tokens in the long form
t = len(blf.replace('-', ' ').split(' '))
# --- c = the number of alphanumeric characters in the acronym
c = sum([int(char.isalpha() or char.isdigit()) for char in acronym])
# --- case-insensitive matching; NOTE: blf is already in lowercase
acronym = acronym.lower().replace(' ', '')
# --- sanity check
if len(blf) < 8: # --- long form too short
return None
elif len(blf) <= len(acronym): # --- long form < short form
return None
elif blf.startswith(acronym + ' '): # --- acronym nested in the long form
return None
elif blf.find(' ' + acronym + ' ') > -1: # --- acronym nested in the long form
return None
elif blf.endswith(' ' + acronym): # --- acronym nested in the long form
return None
elif acronym[0:1] != blf[0:1]: # --- they don't start with the same letter
return None
elif t > 2*c or t > c+5: # --- too many tokens in the long form
return None
elif blf.find('[') >= 0 or blf.find(']') >= 0:
return None
else: # --- no match in the last two tokens
tokens = blf.split()
if len(tokens) > 2:
last2 = " ".join(tokens[-2:])
if last2 == last2.replace(acronym[-1], ""):
return None
# --- delete all other letters from the definition: a token with no match will disappear
remainder = re.sub("[^ "+acronym.replace('-', '')+"]", "", blf)
tokens = len(remainder.split())
#if len(acronym) - tokens >= 2: # --- at least two unmatched tokens
if len(blf.split()) - tokens >= 2: # --- at least two unmatched tokens
return None
return blf
# # --- explicit acronym recognition
# --- compare two acronym definitions and return the preferred one
def preferred(acronym, definition1, definition2):
# --- lemmatise and lowercase both definitions
def1 = " ".join([token.lemma_.lower() for token in nlp(definition1.replace('-', ' '))])
def2 = " ".join([token.lemma_.lower() for token in nlp(definition2.replace('-', ' '))])
def1_def2 = pad(def1)
for token in def2.split(): def1_def2 = re.sub(pad(token), " ", def1_def2)
def1_def2 = def1_def2.strip()
def2_def1 = pad(def2)
for token in def1.split(): def2_def1 = re.sub(pad(token), " ", def2_def1)
def2_def1 = def2_def1.strip()
if def1_def2 == "": # --- nuclear factor kappa B vs nuclear REGULATORY factor kappa B
if len(acronym) == len(def2.split()): # --- prefer potential initialism
return definition2
else:
return definition1
elif def2_def1 == "": # --- nuclear REGULATORY factor kappa B vs nuclear factor kappa B
if len(acronym) == len(def1.split()): # --- prefer potential initialism
return definition1
else:
return definition2
elif bestLongForm(def1_def2, def2_def1) == def2_def1: # --- GC receptor vs glucocorticoid receptor
return definition2
elif bestLongForm(def2_def1, def1_def2) == def1_def2: # --- glucocorticoid receptor vs GC receptor
return definition1
else:
sim = jellyfish.jaro_winkler_similarity(def1, def2)
if sim < 0.7: # --- ambiguous acronym
return 'xxx'
elif len(def1_def2) < len(def2_def1): # --- keep the shorter one
return definition1
else:
return definition2
def explicit_acronyms():
###
cur1.execute("DELETE FROM term_acronym;")
###
dictionary = {} # --- create a JSON dictionary of short/long forms
# --- extract sentences that contain a pair of parentheses, e.g.
# ... blah blah ( blah blah ) blah blah ...
cur1.execute("SELECT sentence FROM data_sentence WHERE tags LIKE '%-LRB- % -RRB-%';")
rows1 = cur1.fetchall()
for row1 in rows1:
sentence = row1[0]
# --- extract all acronym definitions
pairs = extractPairs(sentence)
for i in range(len(pairs)):
# --- parse definition by spacy so that it is comparable to previously extracted MWT candidates
definition = nlp(pairs[i][1])
# --- store definition to the dictionary
acronym = pairs[i][0]
value = " ".join([token.text for token in definition])
cur2.execute("INSERT INTO tmp_acronym(acronym, phrase) VALUES(?,?);", (acronym, value)) # --- for debugging
if acronym in dictionary.keys():
dictionary[acronym] = preferred(acronym, value, dictionary[acronym])
else:
dictionary[acronym] = value
# --- print dictionary to log
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(dictionary)
# --- store acronyms as MWT candidates
for key in dictionary.keys():
phrase = dictionary[key]
if phrase != 'xxx': # --- ignore ambiguous acronyms
cur1.execute("""INSERT INTO term_acronym(acronym, phrase, normalised)
SELECT DISTINCT ?, ?, normalised
FROM term_phrase
WHERE LOWER(?) = LOWER(phrase);""", (key, phrase, phrase))
return
# # --- implicit acronym recognition
# --- assumptions:
# (1) acronyms are frequently used
# (2) expanded form also used in the corpus, but
# these two are probably not linked explicitly
# e.g. blah ACL blah blah ACL blah blah anterior cruciate ligament blah blah
# ~~~ ~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~
# --- find tokens that are potential acronyms:
# (1) must contain an UPPERCASE letter, but no lowercase letters
# (2) must not start with - (avoids e.g. -LRB-)
# (3) must not end with . (avoids MR. so and so)
# (4) has to be at least 3 characters long as shorter ones are
# likely to introduce false positive expanded forms as they
# are more likely to match a random phrase as an expanded form
# candidate
# (5) acronyms are frequently used, so a threshold is set to >MIN times
def implicit_acronyms():
cur1.execute("DELETE FROM tmp_acronym;")
cur1.execute("DELETE FROM term_acronym;")
# --- find tokens that look like acronyms
cur1.execute("""SELECT token, COUNT(*)
FROM data_token
WHERE UPPER(token) = token
AND LENGTH(token) < 6
AND token GLOB '[A-Z][A-Z]*[A-Z]'
GROUP BY token
HAVING COUNT(*) > ?;""", (Amin,))
rows1 = cur1.fetchall()
for row1 in rows1:
acronym = row1[0]
length = len(acronym)
pattern = ""
# --- create a LIKE pattern to retrieve matching phrases
for i in range (0, length): pattern += acronym[i] + "% "
pattern = pattern.strip()
# --- extract potential expanded forms
cur2.execute("""INSERT INTO tmp_acronym(acronym, normalised)