-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2162 lines (2089 loc) · 95.3 KB
/
main.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
########################################################
# Data-Driven Data Science Syllabus Generation #
# Given a text corpus of data science publications, #
# construt a faceted concept hierarchy of #
# data science in lightly-supervised way. #
# Author: Meng Jiang ([email protected]) #
# Version: #
# v1.0 - March 10, 2018: Hearst Pattern matching #
########################################################
import sys
MAXINF = 999999
MAXDIST = 10
# This function prepares the following input files:
# (1) vocabulary.txt
# Each line is a concept word/phrase.
# If the concept is in lower case, we assume it is case insensitive;
# if the concept has at least one upper case, we assume it is case sensitiive.
# Concepts in the text corpus will be recognized if they are in this list.
# (2) patterns.txt
# Each line has multiple columns.
# Column 1: textual pattern (Hearst pattern, etc.)
# $: concept
# <pl>: plural "-s"
# Column 2-: each column is a relation.
# <synonym/ancestor/sibling> <order of left entity> <order of right entity> <if has context>
# synonym(left,right): symmetric
# ancestor(left,right): asymmetric
# sibling(left,right): symmetric
def step0():
# Given syllabus.txt, which is
# ground truth of the data science syllabus (faceted concept hierarchy),
# output the vocabulary of data science concepts.
fw = open('input/vocabulary.txt','w')
fr = open('input/syllabus.txt','r')
for line in fr:
text = line.strip('\r\n')
pos = text.rfind('-->')
entity = text[0:pos]
if '_' in entity:
pos = entity.find('_')
entity = entity[pos+1:]
fw.write(entity+'\n')
fr.close()
fw.close()
# Output textual patterns and their corresponding relations.
# The biggest number of $ is 5.
fw = open('input/patterns.txt','w')
# '$ ( $ )' --> synonym(1,2,F)
fw.write('$ ( $ )' \
+'\t'+'synonym_1_2_F' \
+'\n')
# '$ and/or $ <pl>' --> sibling(1,2,T)
for head in ['$']:
for body in ['and','or']:
for tail in ['$ <pl>']:
fw.write(head+' '+body+' '+tail \
+'\t'+'sibling_1_2_T' \
+'\n')
# '<pl> {,} such as/including/especially $ {,/and/or $}*' --> sibling(1,2,T)
for head in ['<pl>','<pl> ,']:
for body in ['such as','including','especially']:
for tail in ['$ , $','$ and $','$ or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'sibling_1_2_T' \
+'\n')
for tail in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'sibling_1_2_T' \
+'\t'+'sibling_1_3_T' \
+'\t'+'sibling_2_3_T' \
+'\n')
for tail in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'sibling_1_2_T' \
+'\t'+'sibling_1_3_T' \
+'\t'+'sibling_1_4_T' \
+'\t'+'sibling_2_3_T' \
+'\t'+'sibling_2_4_T' \
+'\t'+'sibling_3_4_T' \
+'\n')
# 'such as/including/especially $ {,/and/or $}*' --> sibling(1,2,F)
for body in ['such as','including','especially']:
for tail in ['$ , $','$ and $','$ or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_F' \
+'\n')
for tail in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_F' \
+'\t'+'sibling_1_3_F' \
+'\t'+'sibling_2_3_F' \
+'\n')
for tail in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_F' \
+'\t'+'sibling_1_3_F' \
+'\t'+'sibling_1_4_F' \
+'\t'+'sibling_2_3_F' \
+'\t'+'sibling_2_4_F' \
+'\t'+'sibling_3_4_F' \
+'\n')
# 'such <pl> as $ {,/and/or $}*' --> sibling(1,2,T)
for body in ['such <pl> as']:
for tail in ['$ , $','$ and $','$ or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_T' \
+'\n')
for tail in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_T' \
+'\t'+'sibling_1_3_T' \
+'\t'+'sibling_2_3_T' \
+'\n')
for tail in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_T' \
+'\t'+'sibling_1_3_T' \
+'\t'+'sibling_1_4_T' \
+'\t'+'sibling_2_3_T' \
+'\t'+'sibling_2_4_T' \
+'\t'+'sibling_3_4_T' \
+'\n')
# '$ <pl> {,} such as/including/especially $ {,/and/or $}*' --> ancestor(1,2,T) sibling(2,3,T)
for head in ['$ <pl>','$ <pl> ,']:
for body in ['such as','including','especially']:
for tail in ['$']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_T'+'\n')
for tail in ['$ , $','$ and $','$ or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_T' \
+'\t'+'ancestor_1_3_T' \
+'\t'+'sibling_2_3_T' \
+'\n')
for tail in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_T' \
+'\t'+'ancestor_1_3_T' \
+'\t'+'ancestor_1_4_T' \
+'\t'+'sibling_2_3_T' \
+'\t'+'sibling_2_4_T' \
+'\t'+'sibling_3_4_T' \
+'\n')
for tail in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_T' \
+'\t'+'ancestor_1_3_T' \
+'\t'+'ancestor_1_4_T' \
+'\t'+'ancestor_1_5_T' \
+'\t'+'sibling_2_3_T' \
+'\t'+'sibling_2_4_T' \
+'\t'+'sibling_2_5_T' \
+'\t'+'sibling_3_4_T' \
+'\t'+'sibling_3_5_T' \
+'\t'+'sibling_4_5_T' \
+'\n')
# '$ {,} such as/including/especially $ {,/and/or $}*' --> ancestor(1,2,F) sibling(2,3,F)
for head in ['$','$ ,']:
for body in ['such as','including','especially']:
for tail in ['$']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_F'+'\n')
for tail in ['$ , $','$ and $','$ or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_F' \
+'\t'+'ancestor_1_3_F' \
+'\t'+'sibling_2_3_F' \
+'\n')
for tail in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_F' \
+'\t'+'ancestor_1_3_F' \
+'\t'+'ancestor_1_4_F' \
+'\t'+'sibling_2_3_F' \
+'\t'+'sibling_2_4_F' \
+'\t'+'sibling_3_4_F' \
+'\n')
for tail in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(head+' '+body+' '+tail \
+'\t'+'ancestor_1_2_F' \
+'\t'+'ancestor_1_3_F' \
+'\t'+'ancestor_1_4_F' \
+'\t'+'ancestor_1_5_F' \
+'\t'+'sibling_2_3_F' \
+'\t'+'sibling_2_4_F' \
+'\t'+'sibling_2_5_F' \
+'\t'+'sibling_3_4_F' \
+'\t'+'sibling_3_5_F' \
+'\t'+'sibling_4_5_F' \
+'\n')
# 'such $ as $ {,/and/or $}*' --> ancestor(1,2,F) sibling(2,3,F)
for body in ['such $ as']:
for tail in ['$']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_2_F'+'\n')
for tail in ['$ , $','$ and $','$ or $']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_2_F' \
+'\t'+'ancestor_1_3_F' \
+'\t'+'sibling_2_3_F' \
+'\n')
for tail in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_2_F' \
+'\t'+'ancestor_1_3_F' \
+'\t'+'ancestor_1_4_F' \
+'\t'+'sibling_2_3_F' \
+'\t'+'sibling_2_4_F' \
+'\t'+'sibling_3_4_F' \
+'\n')
for tail in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_2_F' \
+'\t'+'ancestor_1_3_F' \
+'\t'+'ancestor_1_4_F' \
+'\t'+'ancestor_1_5_F' \
+'\t'+'sibling_2_3_F' \
+'\t'+'sibling_2_4_F' \
+'\t'+'sibling_2_5_F' \
+'\t'+'sibling_3_4_F' \
+'\t'+'sibling_3_5_F' \
+'\t'+'sibling_4_5_F' \
+'\n')
# '$ {,/and/or $}* {,} and/or other $' --> ancestor(-1,1,F) sibling(1,2,F)
for tail in ['and other $','or other $',', and other $',', or other $']:
for body in ['$']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_2_F'+'\n')
for body in ['$ , $','$ and $','$ or $']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_3_F' \
+'\t'+'ancestor_2_3_F' \
+'\t'+'sibling_1_2_F' \
+'\n')
for body in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_4_F' \
+'\t'+'ancestor_2_4_F' \
+'\t'+'ancestor_3_4_F' \
+'\t'+'sibling_1_2_F' \
+'\t'+'sibling_1_3_F' \
+'\t'+'sibling_2_3_F' \
+'\n')
for body in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'ancestor_1_5_F' \
+'\t'+'ancestor_2_5_F' \
+'\t'+'ancestor_3_5_F' \
+'\t'+'ancestor_4_5_F' \
+'\t'+'sibling_1_2_F' \
+'\t'+'sibling_1_3_F' \
+'\t'+'sibling_1_4_F' \
+'\t'+'sibling_2_3_F' \
+'\t'+'sibling_2_4_F' \
+'\t'+'sibling_3_4_F' \
+'\n')
# '$ {,/and/or $}* {,} and/or other <pl>' --> sibling(1,2,T)
for tail in ['and other <pl>','or other <pl>',', and other <pl>',', or other <pl>']:
for body in ['$ , $','$ and $','$ or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_F' \
+'\n')
for body in ['$ , $ , $','$ , $ and $','$ , $ , and $','$ , $ or $','$ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_F' \
+'\t'+'sibling_1_3_F' \
+'\t'+'sibling_2_3_F' \
+'\n')
for body in ['$ , $ , $ , $','$ , $ , $ and $','$ , $ , $ , and $','$ , $ , $ or $','$ , $ , $ , or $']:
fw.write(body+' '+tail \
+'\t'+'sibling_1_2_F' \
+'\t'+'sibling_1_3_F' \
+'\t'+'sibling_1_4_F' \
+'\t'+'sibling_2_3_F' \
+'\t'+'sibling_2_4_F' \
+'\t'+'sibling_3_4_F' \
+'\n')
fw.close()
# This function removes REFERENCE(S) section and citations ([x,y,z]) from a document
def rmref(text):
ret = ''
if 'REFERENCE' in text:
pos = text.find('REFERENCE')
text = text[0:pos]
while '[' in text:
pos1 = text.find('[')
ret += text[0:pos1]
text = text[pos1+1:]
if not ']' in text:
return ret+text
pos2 = text.find(']')
text = text[pos2+1:]
return ret+text
# This function recognizes concepts of the vocabulary in the documents,
# and compress the documents for only concepts and their significant contexts
# - non-contextual parts are represented as "#<number of words skipped>".
def step1():
# How many neighboring words around a concept will be shown? When <= SIZE_NEIGHBOR.
SIZE_NEIGHBOR = 5
# How many consecutive non-contextual words between concepts will be skipped? When > SIZE_WINDOW.
SIZE_WINDOW = 20
indexI,nindexI = [{}],1 # Insensitive entity/concept name's word index
indexS,nindexS = [{}],1 # Sensitive entity/concept name's word index
# Build case-(in)sensitive word indices (Trie trees) for concepts
fr = open('input/vocabulary.txt','r')
for line in fr:
entity = line.strip('\r\n')
words = entity.split(' ')
n = len(words)
if entity.lower() == entity: # When case insensitive
if n > nindexI:
for i in range(nindexI,n):
indexI.append({})
nindexI = n
temp = indexI[n-1]
if n > 1:
for i in range(n-1):
word = words[i]
if not word in temp:
temp[word] = {}
temp = temp[word]
word = words[n-1]
else:
word = words[0]
temp[word] = entity.replace(' ','_')
else: # When case sensitive
if n > nindexS:
for i in range(nindexS,n):
indexS.append({})
nindexS = n
temp = indexS[n-1]
if n > 1:
for i in range(n-1):
word = words[i]
if not word in temp:
temp[word] = {}
temp = temp[word]
word = words[n-1]
else:
word = words[0]
temp[word] = entity.replace(' ','_')
fr.close()
# Count the number of docs for progress bar
ndoc = 0
fr = open('input/data.txt','r')
for line in fr:
ndoc += 1
fr.close()
# Given documents, recognize concepts and compress for significant contexts
# data.txt
# Column 1: document id
# Column 2: document's tokenized text
fw = open('output/step1.txt','w')
fr = open('input/data.txt','r')
idoc = 0
for line in fr:
# Show progress bar
idoc += 1
if idoc % 10 == 0 or idoc == ndoc:
sys.stdout.write('\r\tProgress: '+str(0.01*int(10000.0*idoc/ndoc))+'%'+' Doc. '+str(idoc)+' / '+str(ndoc)+' ')
sys.stdout.flush()
# Recognize concepts by DFS tree branch search
output = ''
entityset = set()
pid,text = line.strip('\r\n').split('\t')
text = rmref(text)
words = text.split(' ')
wordsS = []
for word in words:
if word == '': continue
wordsS.append(word)
wordsI = [word.lower() for word in wordsS]
l = len(wordsS)
i = 0
while i < l:
isvalid = False
for j in range(min(nindexI,l-i),0,-1): # Priority for longest phrases
temp = indexI[j-1]
k = 0
while k < j and i+k < l:
tempword = wordsI[i+k]
if not tempword in temp: break
temp = temp[tempword]
k += 1
if k == j:
entity = temp
surface = ''
for _k in range(0,j):
surface += '_'+wordsS[i+_k]
output += ' $e:'+surface[1:]+':'+entity
isvalid = True
break
if isvalid:
i += k
continue
for j in range(min(nindexS,l-i),0,-1):
temp = indexS[j-1]
k = 0
while k < j and i+k < l:
tempword = wordsS[i+k]
if not tempword in temp: break
temp = temp[tempword]
k += 1
if k == j:
entity = temp
surface = ''
for _k in range(0,j):
surface += '_'+wordsS[i+_k]
output += ' $e:'+surface[1:]+':'+entity # Label the concept as "$e:<Surface>:<Entity>"
isvalid = True
break
if isvalid:
i += k
continue
if not wordsS[i] == '':
output += ' '+wordsS[i]
i += 1
text = output[1:]
# Compress documents by skipping non-significant contexts
output = ''
words = text.split(' ')
l = len(words)
i = 0
wordsInterm = []
while i < l:
if words[i].startswith('$e:'):
nInterm = len(wordsInterm)
if nInterm > SIZE_WINDOW:
for k in range(SIZE_NEIGHBOR):
output += ' '+wordsInterm[k]
output += ' #'+str(nInterm-2*SIZE_NEIGHBOR)
for k in range(nInterm-SIZE_NEIGHBOR,nInterm):
output += ' '+wordsInterm[k]
else:
for word in wordsInterm:
output += ' '+word
output += ' '+words[i]
i += 1
wordsInterm = []
continue
wordsInterm.append(words[i])
i += 1
nInterm = len(wordsInterm)
if nInterm > SIZE_WINDOW:
for k in range(SIZE_NEIGHBOR):
output += ' '+wordsInterm[k]
output += ' #'+str(nInterm-SIZE_NEIGHBOR)
else:
for word in wordsInterm:
output += ' '+word
text = output[1:]
# Output document id along with compressed concept-recognized text
fw.write(pid+'\t'+text+'\n')
fr.close()
fw.close()
# This function types the entities into four categories:
# (1) PROBLEM: a research problem or an application;
# (2) METHOD: a methodology or a computational model;
# (3) CONCEPT: a concept/term used in some method;
# (4) METRIC: an evaluation metric for some problem.
# The typing algorithm is based on majority voting with neighboring trigger words,
# so called MajVote-Trigger
def step2():
# Read list of stopwords
stopwordset = set()
fr = open('input/stopwords.txt','r')
for line in fr:
stopwordset.add(line.strip('\r\n'))
fr.close()
# Count the number of docs for progress bar
ndoc = 0
fr = open('output/step1.txt','r')
for line in fr:
ndoc += 1
fr.close()
# Count left/right neighbor words of concepts (lower case)
entity2count = {}
entity2neighbor2count = {} # Left neighbors and right neighbors
fr = open('output/step1.txt','r')
idoc = 0
for line in fr:
# Show progress bar
idoc += 1
if idoc % 10 == 0 or idoc == ndoc:
sys.stdout.write('\r\tProgress: '+str(0.01*int(10000.0*idoc/ndoc))+'%'+' Doc. '+str(idoc)+' / '+str(ndoc)+' ')
sys.stdout.flush()
# Read through the document and count neighbor words
pid,text = line.strip('\r\n').split('\t')
words = text.split(' ')
l = len(words)
for i in range(l):
if not words[i].startswith('$e:'): continue
pos = words[i].rfind(':')
entity = words[i][pos+1:]
if not entity in entity2count:
entity2count[entity] = 0
entity2count[entity] += 1
for j in range(i-1,-1,-1): # Left neighbors
if words[j].startswith('#') or words[j].startswith('$e:') or (len(words[j]) == 1 and not words[j].isalpha()): break
neighbor = words[j].lower()
if neighbor in stopwordset: continue
if neighbor.isalpha():
if not entity in entity2neighbor2count:
entity2neighbor2count[entity] = [{},{}]
if not neighbor in entity2neighbor2count[entity][0]:
entity2neighbor2count[entity][0][neighbor] = 0
entity2neighbor2count[entity][0][neighbor] += 1
for j in range(i+1,l): # Right neighbors
if words[j].startswith('#') or words[j].startswith('$e:') \
or (len(words[j]) == 1 and not words[j].isalpha()): break
neighbor = words[j].lower()
if neighbor in stopwordset: continue
if neighbor.isalpha():
if not entity in entity2neighbor2count:
entity2neighbor2count[entity] = [{},{}]
if not neighbor in entity2neighbor2count[entity][1]:
entity2neighbor2count[entity][1][neighbor] = 0
entity2neighbor2count[entity][1][neighbor] += 1
fr.close()
fw = open('output/step2-support.txt','w')
for [entity,count] in sorted(entity2count.items(),key=lambda x:-x[1]):
fw.write(entity+'\t'+str(count)+'\n')
fw.close()
# Output left/right neighbor words of concepts and their counts
fw = open('output/step2-neighbor.txt','w')
for [entity,[neighbor2countLeft,neighbor2countRight]] in sorted(entity2neighbor2count.items(),key=lambda x:x[0]):
outputLeft = ''
for [neighbor,count] in sorted(neighbor2countLeft.items(),key=lambda x:-x[1]):
outputLeft += ' '+neighbor+'|'+str(count)
if outputLeft == '':
outputLeft = 'NA'
else:
outputLeft = outputLeft[1:]
outputRight = ''
for [neighbor,count] in sorted(neighbor2countRight.items(),key=lambda x:-x[1]):
outputRight += ' '+neighbor+'|'+str(count)
if outputRight == '':
outputRight = 'NA'
else:
outputRight = outputRight[1:]
fw.write(entity+'\t'+outputLeft+'\t'+outputRight+'\n')
fw.close()
# Read the neighbor words and counts
entity2neighbors = {}
fr = open('output/step2-neighbor.txt','r')
for line in fr:
arr = line.strip('\r\n').split('\t')
entity = arr[0]
entity2neighbors[entity] = [[],[]] # left, right
if not arr[1] == 'NA':
for neighborcount in arr[1].split(' '):
neighbor,strcount = neighborcount.split('|')
count = int(strcount)
entity2neighbors[entity][0].append([neighbor,count])
if not arr[2] == 'NA':
for neighborcount in arr[2].split(' '):
neighbor,strcount = neighborcount.split('|')
count = int(strcount)
entity2neighbors[entity][1].append([neighbor,count])
fr.close()
# Read trigger words and their mapping to the type category from
# triggers.txt
# Column 1: trigger word (lower case)
# Column 2: L(eft) or R(ight) neighbor
# Column 3: type category to vote for
tag_pos_tp = []
fr = open('input/triggers.txt','r')
for line in fr:
tag_pos_tp.append(line.strip('\r\n').split('\t'))
fr.close()
# MajVote-Trigger: Predict concept type given neighbor words
entity2tppredict = {}
fw = open('output/step2-typing.txt','w')
fr = open('input/vocabulary.txt','r')
for line in fr:
entity = line.strip('\r\n')
entity = entity.replace(' ','_')
tp2count = {}
if entity in entity2neighbors:
for [tag,pos,tp] in tag_pos_tp:
if pos == 'L':
for [neighbor,count] in entity2neighbors[entity][0]:
if tag == neighbor:
if not tp in tp2count:
tp2count[tp] = 0
tp2count[tp] += count
elif pos == 'R':
for [neighbor,count] in entity2neighbors[entity][1]:
if tag == neighbor:
if not tp in tp2count:
tp2count[tp] = 0
tp2count[tp] += count
tp_count = sorted(tp2count.items(),key=lambda x:-x[1])
tpstr = ''
for [tp,count] in tp_count:
tpstr += ' '+tp+'|'+str(count)
tppredict = 'CONCEPT' # The default type is CONCEPT
if not tpstr == '':
tpstr = tpstr[1:]
tppredict = tp_count[0][0] # Predicted as the most voted type
fw.write(entity+'\t'+tppredict+'\t'+tpstr+'\n')
entity2tppredict[entity] = tppredict
fr.close()
fw.close()
# Evaluate concept typing based on the ground truth "syllabus"
flag2count = {}
fw = open('output/step2-typing-evaluate.txt','w')
fr = open('input/syllabus.txt','r')
for line in fr:
text = line.strip('\r\n')
pos = text.rfind('-->')
tptruth = text[pos+3:]
entity = text[0:pos]
if '_' in entity:
pos = entity.find('_')
entity = entity[pos+1:]
entity = entity.replace(' ','_')
tppredict = entity2tppredict[entity]
flag = 'F'
if tppredict == tptruth:
flag = 'T'
if not flag in flag2count:
flag2count[flag] = 0
flag2count[flag] += 1
fw.write(entity+'\t'+tptruth+'\t'+tppredict+'\t'+flag+'\n')
fr.close()
s = '#'
nT,nAll = 0,0
for [flag,count] in sorted(flag2count.items(),key=lambda x:x[0]):
s += ' '+flag+'|'+str(count)
if flag == 'T':
nT += count
nAll += count
accuracy = 1.0*nT/nAll
fw.write(s+'\t'+str(accuracy)+'\n')
fw.close()
print('\n\tTyping accuracy (MajVote-Trigger): '+str(accuracy))
# Replace "e" as the type for each concept in the compressed corpus
fw = open('output/step2.txt','w')
fr = open('output/step1.txt','r')
for line in fr:
output = ''
pid,text = line.strip('\r\n').split('\t')
words = text.split(' ')
l = len(words)
for i in range(l):
if words[i].startswith('$e:'):
pos = words[i].rfind(':')
entity = words[i][pos+1:]
tp = entity2tppredict[entity]
pos = words[i].find(':')
output += ' $'+tp+words[i][pos:]
else:
output += ' '+words[i]
fw.write(pid+'\t'+output[1:]+'\n')
fr.close()
fw.close()
# This function extracts relations of three types:
# (1) synonym(left,right): symmetric
# (2) ancestor(left,right): asymmetric
# (3) sibling(left,right): symmetric
# by Hearst (Hearst Pattern Matching)
def step3():
index,nindex = [{}],1 # textual pattern's element index
# Build pattern element index (Trie tree) for pattern matching
fr = open('input/patterns.txt','r')
for line in fr:
arr = line.strip('\r\n').split('\t')
pattern = arr[0]
mapping = []
for i in range(1,len(arr)):
_arr = arr[i].split('_')
reltype = _arr[0]
ordleft = int(_arr[1])
ordright = int(_arr[2])
enablepl = _arr[3]
mapping.append([reltype,ordleft,ordright,enablepl])
words = pattern.split(' ')
n = len(words)
if n > nindex:
for i in range(nindex,n):
index.append({})
nindex = n
temp = index[n-1]
if n > 1:
for i in range(n-1):
word = words[i]
if not word in temp:
temp[word] = {}
temp = temp[word]
word = words[n-1]
else:
word = words[0]
temp[word] = [pattern,pattern.split(' '),mapping]
fr.close()
# Count the number of docs for progress bar
ndoc = 0
fr = open('output/step2.txt','r')
for line in fr:
ndoc += 1
fr.close()
# Relation extraction using pattern matching
# Output pattern matching
# Column 1: Hearst pattern
# Column 2: Matched segment in the document
relation2count = {}
fw = open('output/step3-pattern.txt','w')
fr = open('output/step2.txt','r')
idoc = 0
for line in fr:
# Show progress bar
idoc += 1
if idoc % 10 == 0 or idoc == ndoc:
sys.stdout.write('\r\tProgress: '+str(0.01*int(10000.0*idoc/ndoc))+'%'+' Doc. '+str(idoc)+' / '+str(ndoc)+' ')
sys.stdout.flush()
# Pattern matching using Trie tree search
words = line.strip('\r\n').split(' ')
l = len(words)
i = 0
while i < l:
isvalid = False
for j in range(min(nindex,l-i),0,-1):
temp = index[j-1]
k = 0
while k < j and i+k < l:
tempword = words[i+k]
if tempword == '$':
tempword = 'USD'
elif tempword.startswith('$'):
tempword = '$'
elif len(tempword) > 3 and tempword.endswith('s') and '<pl>' in temp:
tempword = '<pl>'
if not tempword in temp: break
temp = temp[tempword]
k += 1
if k == j:
pattern,elems,mapping = temp
for [reltype,ordleft,ordright,enablepl] in mapping:
posleft,posright,pospls = -1,-1,[]
_ord = 0
for _i in range(0,len(elems)):
if elems[_i] == '$':
_ord += 1
if _ord == ordleft:
posleft = _i
if _ord == ordright:
posright = _i
if enablepl == 'T' and elems[_i] == '<pl>':
pospls.append(_i)
if posleft < 0 or posright < 0: continue
relation = ''
_posleft = words[i+posleft].rfind(':')
_posright = words[i+posright].rfind(':')
_posleft_ = words[i+posleft].find(':')
_posright_ = words[i+posright].find(':')
surfaceleft = words[i+posleft][_posleft_+1:_posleft]
surfaceright = words[i+posright][_posright_+1:_posright]
entityleft = words[i+posleft][_posleft+1:]
entityright = words[i+posright][_posright+1:]
if entityleft == entityright: continue
context = ''
if len(pospls) > 0:
for pospl in pospls:
context += ' '+words[i+pospl]
context = context[1:]
relation = reltype+'\t'+entityleft+'\t'+entityright # +'\t'+context # context ignored
if not relation in relation2count:
relation2count[relation] = 0
relation2count[relation] += 1
surface = ''
for _k in range(0,j):
surface += ' '+words[i+_k]
fw.write(pattern+'\t'+surface[1:]+'\n')
isvalid = True
break
if isvalid:
i += k
continue
i += 1
fr.close()
fw.close()
# Output relations
# Column 1: relation type
# Column 2: left entity
# Column 3: right entity
# (context ignored)
# Column 4: count
fw = open('output/step3-relation.txt','w')
for [relation,count] in sorted(relation2count.items(),key=lambda x:-x[1]):
fw.write(relation+'\t'+str(count)+'\n')
fw.close()
# This function conducts the following tasks:
# (1) Synonym clustering: group synonym concepts into a cluster;
# (2) Sibling clustering: group sibling concept clusters into a level cluster;
# (3) Re-typing: assume that synonym/sibling concepts have the same type;
# (4) Typing evaluation: re-evaluate the refined typing results.
def step4():
# parameter: trust the sibling relation if count >= MIN_COUNT_SIBLING
MIN_COUNT_SIBLING = 3
# Relation: (relation type, left entity, right entity, count)
relation_count = []
# Synonym amended
fr = open('input/domainknowledge.txt','r')
for line in fr:
arr = line.strip('\r\n').split(' ')
concept1,concept2,reltype = arr[0],arr[1],arr[2]
relation_count.append([reltype,concept1,concept2,MAXINF])
fr.close()
concepts = []
fr = open('output/step2-typing.txt','r')
for line in fr:
arr = line.strip('\r\n').split('\t')
concept = arr[0]
concepts.append(concept)
fr.close()
concepts = sorted(concepts)
nConcept = len(concepts)
for i in range(0,nConcept-1):
if concepts[i]+'s' == concepts[i+1] or \
concepts[i].replace('-','_') == concepts[i+1].replace('-','_') or \
(concepts[i+1].count('_') == concepts[i].count('_')+1 and concepts[i+1].startswith(concepts[i]+'_')):
relation_count.append(['synonym',concepts[i],concepts[i+1],MAXINF])
# Read relation
fr = open('output/step3-relation.txt','r')
for line in fr:
arr = line.strip('\r\n').split('\t')
reltype = arr[0]
entityleft = arr[1]
entityright = arr[2]
count = int(arr[3])
relation_count.append([reltype,entityleft,entityright,count])
fr.close()
# Group synonym concepts/entities into clusters
entity2clustername = {} # entity -> cluster
clustername2entityset = {} # entity cluster -> set of entities
entity2nonsynonymset = {} # if not synonyms...
for [reltype,entityleft,entityright,count] in relation_count:
if count < 2: break
if not reltype == 'synonym':
if not entityleft in entity2nonsynonymset:
entity2nonsynonymset[entityleft] = set()
entity2nonsynonymset[entityleft].add(entityright)
if not entityright in entity2nonsynonymset:
entity2nonsynonymset[entityright] = set()
entity2nonsynonymset[entityright].add(entityleft)
for [reltype,entityleft,entityright,count] in relation_count:
if not reltype == 'synonym': continue
if (entityleft in entity2nonsynonymset and entityright in entity2nonsynonymset[entityleft]) \
or (entityright in entity2nonsynonymset and entityleft in entity2nonsynonymset[entityright]):
continue
if entityleft[0].isalpha() and entityright[0].isalpha() \
and not entityleft[0].lower() == entityright[0].lower():
continue
if entityleft in entity2clustername and entityright in entity2clustername:
clusterleft = entity2clustername[entityleft]
clusterright = entity2clustername[entityright]
if not clusterleft == clusterright:
entityset = set()
entityset = entityset | clustername2entityset[clusterleft]
entityset = entityset | clustername2entityset[clusterright]
entitylist = sorted(entityset,key=lambda x:-len(x))
clustername = entitylist[0]
del clustername2entityset[clusterleft]
del clustername2entityset[clusterright]
for entity in entityset:
entity2clustername[entity] = clustername
clustername2entityset[clustername] = entityset
elif entityleft in entity2clustername and not entityright in entity2clustername:
clustername = entity2clustername[entityleft]
entity2clustername[entityright] = clustername
clustername2entityset[clustername].add(entityright)
elif not entityleft in entity2clustername and entityright in entity2clustername:
clustername = entity2clustername[entityright]
entity2clustername[entityleft] = clustername
clustername2entityset[clustername].add(entityleft)
else:
entityset = set([entityleft,entityright])
entitylist = sorted(entityset,key=lambda x:-len(x))
clustername = entitylist[0]
entity2clustername[entityleft] = clustername
entity2clustername[entityright] = clustername
clustername2entityset[clustername] = entityset
# Make single-concept/entity clusters (optional)
for [reltype,entityleft,entityright,count] in relation_count:
if not entityleft in entity2clustername:
entity2clustername[entityleft] = entityleft
clustername2entityset[entityleft] = set([entityleft])
if not entityright in entity2clustername:
entity2clustername[entityright] = entityright
clustername2entityset[entityright] = set([entityright])
# Read ancestor relationship
cluster2ancestorset = {}
for [reltype,entityleft,entityright,count] in relation_count:
if reltype == 'ancestor':
if entityleft in entity2clustername and entityright in entity2clustername:
clusterleft = entity2clustername[entityleft]
clusterright = entity2clustername[entityright]
if not clusterleft in cluster2ancestorset:
cluster2ancestorset[clusterleft] = set()
cluster2ancestorset[clusterleft].add(clusterright)
if not clusterright in cluster2ancestorset:
cluster2ancestorset[clusterright] = set()
cluster2ancestorset[clusterright].add(clusterleft)
# Group sibling concept/entity clusters as a "level" cluster
cluster2level = {}
level2clusterset = {}
for [reltype,entityleft,entityright,count] in relation_count:
if not (reltype == 'sibling' and entityleft in entity2clustername and entityright in entity2clustername):
continue
if count < MIN_COUNT_SIBLING:
continue
clusterleft = entity2clustername[entityleft]
clusterright = entity2clustername[entityright]
if (clusterleft in cluster2ancestorset and clusterright in cluster2ancestorset[clusterleft]) \
or (clusterright in cluster2ancestorset and clusterleft in cluster2ancestorset[clusterright]):
continue
if clusterleft in cluster2level and clusterright in cluster2level:
levelleft = cluster2level[clusterleft]
levelright = cluster2level[clusterright]
if not levelleft == levelright:
clusterset = set()
clusterset = clusterset | level2clusterset[levelleft]
clusterset = clusterset | level2clusterset[levelright]
clusterlist = sorted(clusterset,key=lambda x:-len(x))
level = clusterlist[0]
del level2clusterset[levelleft]
del level2clusterset[levelright]
for cluster in clusterset:
cluster2level[cluster] = level
level2clusterset[level] = clusterset
elif clusterleft in cluster2level and not clusterright in cluster2level:
level = cluster2level[clusterleft]
cluster2level[clusterright] = level
level2clusterset[level].add(clusterright)
elif not clusterleft in cluster2level and clusterright in cluster2level:
level = cluster2level[clusterright]
cluster2level[clusterleft] = level
level2clusterset[level].add(clusterleft)
else:
clusterset = set([clusterleft,clusterright])
clusterlist = sorted(clusterset,key=lambda x:-len(x))
level = clusterlist[0]
cluster2level[clusterleft] = level
cluster2level[clusterright] = level
level2clusterset[level] = clusterset
# Output synonym/sibling concept clusters
fw = open('output/step4-cluster.txt','w')
for [clustername,entityset] in sorted(clustername2entityset.items(),key=lambda x:x[0]):
if len(entityset) == 1: continue
s = ''
for entity in sorted(entityset):
s += '|'+entity
fw.write('synonym'+'\t'+clustername+'\t'+s[1:]+'\n')
for [level,clusterset] in sorted(level2clusterset.items(),key=lambda x:x[0]):
s = ''
for cluster in sorted(clusterset):
s += '|'+cluster
fw.write('sibling'+'\t'+level+'\t'+s[1:]+'\n')
fw.close()
# Read synonym/sibling concept clusters
entity2cluster = {}
cluster2entityset = {}
cluster2level = {}
level2clusterset = {}
fr = open('output/step4-cluster.txt','r')
for line in fr:
arr = line.strip('\r\n').split('\t')