-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathner.py
More file actions
2591 lines (1692 loc) · 74.1 KB
/
ner.py
File metadata and controls
2591 lines (1692 loc) · 74.1 KB
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
import nltk
import sys
import re
import string
import urllib
import pickle
import hashlib
import os
import json
import unicodedata
dataDir = '/home/dbpedia/transcript/data/'
totalSteps = 22
###################3
# We depend on a number of files, make sure they are there, if not, create them
if os.path.exists(dataDir + "blacklist.txt") == False:
f = open(dataDir + "blacklist.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "notNameParts.txt") == False:
f = open(dataDir + "notNameParts.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "globalIgnore.txt") == False:
f = open(dataDir + "globalIgnore.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "regexPatterns.txt") == False:
f = open(dataDir + "regexPatterns.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "globalSameAs.txt") == False:
f = open(dataDir + "globalSameAs.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "globalAuthority.txt") == False:
f = open(dataDir + "globalAuthority.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "globalAuthorityNotes.txt") == False:
f = open(dataDir + "globalAuthorityNotes.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "globalOther.txt") == False:
f = open(dataDir + "globalOther.txt", 'w')
f.writelines("\n")
f.close()
if os.path.exists(dataDir + "publishedFileNames.txt") == False:
f = open(dataDir + "publishedFileNames.txt", 'w')
f.writelines("\n")
f.close()
#load our black list
f = open(dataDir + "blacklist.txt", 'r')
blacklist = f.read().strip()
blacklist = blacklist.strip().lower()
blacklist = blacklist.split("\n")
#load our not a name part
#these are words that should not appear in a name, meaning, it is not a name
f = open(dataDir + "notNameParts.txt", 'r')
notNameParts = f.read().strip()
notNameParts = notNameParts.strip().lower()
notNameParts = notNameParts.split("\n")
f = open(dataDir + "globalIgnore.txt", 'r')
globalIgnore = f.read().strip()
globalIgnore = globalIgnore.split("\n")
f = open(dataDir + "regexPatterns.txt", 'r')
regexPatterns = f.read().strip()
regexPatterns = regexPatterns.split("\n")
f = open(dataDir + "globalOther.txt", 'r')
globalOther = f.read().strip()
globalOther = globalOther.split("\n")
f = open(dataDir + "globalSameAs.txt", 'r')
globalSameAsLines = f.read().strip()
globalSameAsLines = globalSameAsLines.split("\n")
globalSameAs = []
for x in globalSameAsLines:
if x != '':
set = x.split(',')
globalSameAs.append(set)
f = open(dataDir + "globalAuthority.txt", 'r')
globalAuthorityLines = f.read().strip()
globalAuthorityLines = globalAuthorityLines.split("\n")
globalAuthority = []
for x in globalAuthorityLines:
if x != '':
set = x.split(',')
globalAuthority.append(set)
f = open(dataDir + "globalAuthorityNotes.txt", 'r')
globalAuthorityNotesLines = f.read().strip()
globalAuthorityNotesLines = globalAuthorityNotesLines.split("\n")
globalAuthorityNotes = []
for x in globalAuthorityNotesLines:
if x != '':
set = x.split('|')
globalAuthorityNotes.append(set)
def main():
if (len(sys.argv) != 2):
print "Error: No no filename given"
sys.exit()
fileName = dataDir + sys.argv[1]
fileNameOrg = sys.argv[1].replace('.txt','')
authorityNames = {}
authorityNamesList = []
authorityCollisons = []
activeStep = 0
activeStep = activeStep + 1
updateProgress("Loading directory names",fileName,activeStep)
#index is a name, value is its perfered term
sameAs = {}
#jazzData is a extract created by the dictonary creation process, it contains the names and other stuff in triple form
f = open(dataDir + "../../data/jazzData.nt", 'r')
for line in f:
quad = line.split()
#if quad[1] == '<http://www.w3.org/2004/02/skos/core#prefLabel>' or quad[1] == '<http://www.w3.org/2004/02/skos/core#altLabel>' or quad[1] == '<http://xmlns.com/foaf/0.1/name>':
if quad[1] == '<http://xmlns.com/foaf/0.1/name>':
name = ' '.join(quad[2:])
if name.find('@EN') != -1:
name = name[0:name.find('@EN')]
if name.find('@en') != -1:
name = name[0:name.find('@en')]
name = name[1:len(name)-1]
m = re.search("\d", name)
if m:
name = name[0:m.start()]
if name.find(',') != -1:
comma = name.split(',')
newComma = []
hasJrSr = ''
for x in comma:
x=x.strip()
x=x.replace(".","")
if len(x)!=0:
if x == 'Jr' or x == 'Sr' or x == 'II' or x == 'III':
hasJrSr = ' ' + x
else:
newComma.append(x)
nameFinal = ''.join(comma[1:]) + ' ' + comma[0] + hasJrSr
nameFinal = nameFinal.replace(' ',' ')
nameFinal = nameFinal.strip()
name = nameFinal
name = name.replace("Jr.","Jr")
name = name.replace("Sr.","Sr")
name = name.strip()
if quad[0].find('/resource/') != -1:
uriName = formatName(quad[0].split('/resource/')[1])
uriName = uriName.replace(",","")
uriName = uriName.replace("Jr.","Jr")
uriName = uriName.replace("Sr.","Sr")
uriName = uriName.strip()
#if len(uriName.split()) >1:
if authorityNames.has_key(uriName):
if authorityNames[uriName] != quad[0]:
#print "Collison",authorityNames[uriName], quad[0]
if authorityNames[uriName] not in authorityCollisons:
authorityCollisons.append(authorityNames[uriName])
authorityNames[uriName] = quad[0]
#if len(name.split()) >1:
if authorityNames.has_key(name):
if authorityNames[name] != quad[0]:
#print "Collison",authorityNames[name], quad[0]
if authorityNames[name] not in authorityCollisons:
authorityCollisons.append(authorityNames[name])
authorityNames[name] = quad[0]
#LOC
elif quad[1] == '<http://www.w3.org/2004/02/skos/core#prefLabel>' or quad[1] == '<http://www.w3.org/2004/02/skos/core#altLabel>':
name = ' '.join(quad[2:])
if name.find('@EN') != -1:
name = name[0:name.find('@EN')]
if name.find('@en') != -1:
name = name[0:name.find('@en')]
name = name[1:len(name)-1]
name = name.strip()
#just included the first and last name. (which may not be last name, but LOC labels way too variable to devote too much time on)
name = name.split(',')
if len(name) > 1:
name = name[1] + ' ' + name[0]
name = name.strip()
#more useful if the dbpedia url
if authorityNames.has_key(name) == False:
authorityNames[name] = quad[0]
f.close()
#for name, uri in authorityNames.iteritems():
# print name,uri
#load the words corpus
wordCorpusFile = nltk.data.load('nltk:corpora/words/en','raw')
wordCorpusFile = wordCorpusFile.strip()
wordCorpusFile = wordCorpusFile.split("\n")
wordCorpus={}
for word in wordCorpusFile:
wordCorpus[word] = word
firstNames={}
f = open("/home/dbpedia/extracts/firstNames.txt", 'r')
firstNamesFile = f.read().strip()
firstNamesFile = firstNamesFile.replace("\r",'')
firstNamesFile = firstNamesFile.split("\n")
for name in firstNamesFile:
firstNames[name] = name
assumtions = []
interviewees=[]
interviewers=[]
foundNames = []
possiblePartials = []
fullTextReplace = []
#reporting Vars
namesMatched=[]
namesNLP=[]
allSentences = []
#other non name entities
otherEnts = []
nlpData = []
#the user rules passed back from the front end
userRulesIgnoreLocal = []
userRulesIgnoreGlobal = []
userRulesOtherNames = []
userRulesSameAs = []
userRulesManualNames = []
userRulesIntervieweesNames = []
userRulesIntervieweesSplits = []
userRulesInterviewersNames = []
userRulesInterviewersSplits = []
userRulesSplitRegex = ''
userRulesIgnoreCountTest = False
userRulespartialAprovals = []
userAuthorityControl = []
userPublish = {}
userName = 'none'
activeStep = activeStep + 1
updateProgress("Processing User rules",fileName,activeStep)
f = open(fileName, 'r')
entire_file = f.read()
#we use the md5 of the file to keep track of file names and such
md5 = hashlib.md5()
md5.update(entire_file)
fileMd5 = md5.hexdigest()
#load the user rules if exitsts
if os.path.exists(dataDir + fileMd5 + '_userRules.json'):
f = open(dataDir + fileMd5 + '_userRules.json', 'r')
jsonStr = f.read()
f.close()
jsonObj = json.loads(jsonStr)
if 'ignoreLocal' in jsonObj:
for x in jsonObj['ignoreLocal']:
userRulesIgnoreLocal.append(x)
if 'ignoreGlobal' in jsonObj:
for x in jsonObj['ignoreGlobal']:
userRulesIgnoreGlobal.append(x)
if 'otherName' in jsonObj:
for x in jsonObj['otherName']:
userRulesOtherNames.append(x)
if 'sameAs' in jsonObj:
for x in jsonObj['sameAs']:
x['sameAs'] = strip_accents(x['sameAs'])
x['org'] = strip_accents(x['org'])
userRulesSameAs.append(x)
if 'manualNames' in jsonObj:
for x in jsonObj['manualNames']:
userRulesManualNames.append(x)
if 'intervieweesNames' in jsonObj:
for x in jsonObj['intervieweesNames']:
if x != "":
userRulesIntervieweesNames.append(x)
if 'intervieweesSplits' in jsonObj:
for x in jsonObj['intervieweesSplits']:
if x != "":
userRulesIntervieweesSplits.append(x)
if 'interviewersNames' in jsonObj:
for x in jsonObj['interviewersNames']:
if x != "":
userRulesInterviewersNames.append(x)
if 'interviewersSplits' in jsonObj:
for x in jsonObj['interviewersSplits']:
if x != "":
userRulesInterviewersSplits.append(x)
if 'structureRegexPattern' in jsonObj:
userRulesSplitRegex = jsonObj['structureRegexPattern']
if 'publish' in jsonObj:
userPublish = jsonObj['publish']
if 'userName' in jsonObj:
userName = jsonObj['userName']
if 'authorityControl' in jsonObj:
userAuthorityControl = jsonObj['authorityControl']
if 'structureIgnoreCountTest' in jsonObj:
if jsonObj['structureIgnoreCountTest'] == 'true':
userRulesIgnoreCountTest = True
else:
userRulesIgnoreCountTest = False
if 'partialAprovals' in jsonObj:
userRulespartialAprovals = jsonObj['partialAprovals']
#############
## User rules need to be outputed to a save file if they are global.
for x in userRulesIgnoreGlobal:
try:
globalIgnore.index(x)
except ValueError:
f = open(dataDir + "globalIgnore.txt", 'a')
f.writelines(x + "\n")
f.close()
for x in userRulesOtherNames:
try:
globalOther.index(x)
except ValueError:
f = open(dataDir + "globalOther.txt", 'a')
f.writelines(x + "\n")
f.close()
for x in userAuthorityControl:
set = [x['name'], x['value']]
try:
globalAuthority.index(set)
except ValueError:
f = open(dataDir + "globalAuthority.txt", 'a')
f.writelines(set[0] + ',' + set[1] + "\n")
f.close()
#also write it to the notes file with any notes if it is a coined URI
if 'sourceUrl' in x:
f = open(dataDir + "globalAuthorityNotes.txt", 'a')
f.writelines(set[1] + '|' + x['sourceUrl'] + '|' + x['sourceNotes'] + '|' + userName + "\n")
f.close()
for x in userRulesSameAs:
if len(x['org']) > 5:
set = [x['org'],x['sameAs']]
try:
globalSameAs.index(set)
except ValueError:
f = open(dataDir + "globalSameAs.txt", 'a')
f.writelines(strip_accents(set[0]) + ',' + strip_accents(set[1]) + "\n")
f.close()
#overwrite/add in the authority
for x in globalAuthority:
if x[0] != '' and x[1] != '':
authorityNames[x[0]] = x[1]
for x in userAuthorityControl:
if x['name'] != '' and x['value'] != '':
authorityNames[str(x['name'])] = str(x['value'])
#add in the global sameAs
for x in globalSameAs:
userRulesSameAs.append({ 'org' : x[0], 'sameAs' : x[1]})
#add in the global others
for x in globalOther:
if x not in userRulesOtherNames and x != '':
userRulesOtherNames.append(x)
activeStep = activeStep + 1
updateProgress("Testing question split rules",fileName,activeStep)
#This part tests diffrent regex splits on the whole doc, the idea is to find how the interview questions are split up based on known patterns
#if it cannot determin how it is split it cannot continue, will need to add additonal patterns if differnt transcripts are added
foundQuestionSplit = False
splitType = ""
#the number of splits that has to be inorder for the regex to be considered sucessful, this can vary based on the length of the interview
splitThreshold = 100
#realllly short interview here
if len(entire_file) < 15000:
splitThreshold = 20
if (foundQuestionSplit==False) and userRulesSplitRegex != '':
#user
splited = re.split(userRulesSplitRegex,entire_file)
if (len(splited)>splitThreshold):
foundQuestionSplit = True
splitPattern = userRulesSplitRegex
splitType = "single"
if userRulesSplitRegex not in regexPatterns:
#if the pattern worked, then we want to save it for future use
f = open(dataDir + "regexPatterns.txt", 'a')
f.writelines(userRulesSplitRegex + "\n")
f.close()
else:
if userRulesIgnoreCountTest == True:
#if they force it accept but do not save it.
foundQuestionSplit = True
splitPattern = userRulesSplitRegex
splitType = "single"
else:
print '{"results": {"error": true,"type": "Structure", "msg" : "That Pattern did not work. It only matched ' + str(len(splited)) + ' patterns. If this is a short interview consider using the Ignore count test option if you know it is correct.", "id": "' + fileMd5 + '"}}'
sys.exit()
#smithsonian
if (foundQuestionSplit==False):
splited = re.split(r'[\n]([A-Z][a-z]*:)',entire_file)
#print "smithsonian",len(splited)
if (len(splited)>splitThreshold):
foundQuestionSplit = True
splitPattern = r'([A-Z][a-z]*:)'
splitType = "lastname"
if (foundQuestionSplit==False):
#smithsonian 2
splited = re.split(r'\n([A-Z]*:)\W',entire_file)
#print "hamilton",len(splited)
if (len(splited)>splitThreshold):
foundQuestionSplit = True
splitPattern = r'([A-Z]*:)'
splitType = "lastname"
if (foundQuestionSplit==False):
#hamilton
splited = re.split(r'\W([A-Z]{2}:)\W',entire_file)
#print "hamilton",len(splited)
if (len(splited)>splitThreshold):
foundQuestionSplit = True
splitPattern = r'([A-Z]{2}:)'
splitType = "initals"
#try the saved regex patterns
if (foundQuestionSplit==False):
for x in regexPatterns:
if x != '':
splited = re.split(x,entire_file)
if (len(splited)>splitThreshold):
foundQuestionSplit = True
splitPattern = x
splitType = "single"
#print splitPattern
#print splitType
#sys.exit()
if (foundQuestionSplit==False):
#print "Error: Could not split on the interview questions. Please update the regex split patterns."
print '{"results": {"error": true,"type": "Structure", "msg" : "Need the regular expression split pattern", "id": "' + fileMd5 + '"}}'
sys.exit()
possibleSplits = []
for x in splited:
splitTest = re.split(splitPattern,x)
if len(splitTest) > 1:
if splitTest[1] not in possibleSplits:
possibleSplits.append(splitTest[1])
counter = -1
#we can go two routes here, if there is already the NLP processed data for this file use that otherwise we need to process it
if os.path.exists(dataDir + fileMd5 + '.pkl'):
activeStep = activeStep + 1
updateProgress("Processing NLP data from saved file.", fileName,activeStep)
pkl_file = open(dataDir + fileMd5 + '.pkl', 'rb')
nlpData = pickle.load(pkl_file)
pkl_file.close()
for aSent in nlpData:
#add the sentence into the expected allSentence var
allSentences.append(aSent[0])
counter = counter + 1
#process the chunks
#TODO: This code is repeated below, fix that...
for chunk in aSent[1]:
if hasattr(chunk, 'node'):
if chunk.node == 'PERSON':
#check to see how long it is, one word names are not good
if len(chunk.leaves()) == 1:
#save the partial matches for later
if wordNotBlackListed(chunk.leaves()[0][0]):
possiblePartials.append([chunk.leaves()[0][0], counter])
else:
name = ' '.join(c[0] for c in chunk.leaves())
#make sure the word does not contain any of our black listed words
if wordNotBlackListed(name):
if name not in foundNames:
foundNames.append(name)
else:
word = ' '.join(c[0] for c in chunk.leaves())
if wordNotBlackListed(word):
if [chunk.node,word] not in otherEnts:
otherEnts.append([chunk.node,word])
else:
activeStep = activeStep + 1
updateProgress("Chunking sentences(will take a long time).",fileName,activeStep)
#print "tokenizing entire file"
allSentences = nltk.sent_tokenize(entire_file)
#print "chunking sentences"
for sent in allSentences:
counter = counter + 1
allChunks = nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent)))
#store
nlpData.append([sent,allChunks])
for chunk in allChunks:
if hasattr(chunk, 'node'):
if chunk.node == 'PERSON':
#check to see how long it is, one word names are not good
if len(chunk.leaves()) == 1:
#save the partial matches for later
if wordNotBlackListed(chunk.leaves()[0][0]):
possiblePartials.append([chunk.leaves()[0][0], counter])
else:
name = ' '.join(c[0] for c in chunk.leaves())
#make sure the word does not contain any of our black listed words
if wordNotBlackListed(name):
if name not in foundNames:
foundNames.append(name)
else:
word = ' '.join(c[0] for c in chunk.leaves())
if wordNotBlackListed(word):
if [chunk.node,word] not in otherEnts:
otherEnts.append([chunk.node,word])
#store this data into the filesystem under the md5 of the file as filename. we can then reuse it next time.
output = open(dataDir + fileMd5 + '.pkl', 'wb')
pickle.dump(nlpData, output)
output.close()
activeStep = activeStep + 1
updateProgress("Processing NLP found names",fileName,activeStep)
for name in list(foundNames):
nameStriped = name
nameStriped = nameStriped.replace(",","")
nameStriped = nameStriped.replace("Jr.","Jr")
nameStriped = nameStriped.replace("Sr.","Sr")
if not authorityNames.has_key(nameStriped):
#print "'" + name + "' Not found in the DBpedia name extract"
aName = name.split(' ')
if not firstNames.has_key(aName[0]):
#print "\t" + aName[0] + " not found in the first name file"
if wordCorpus.has_key(aName[len(aName)-1].lower()) or wordCorpus.has_key(aName[len(aName)-1]):
#print "\t" + name + " does not look like a real name to me. And it is not in the directory. And it contains a common word(" + aName[len(aName)-1] + ")."
assumtions.append(name + " does not look like a real/jazz name to me. And it is not in the directory. And it contains a common word(" + aName[len(aName)-1] + "). Removing it from the name list. placinging it in the Other Entities")
otherEnts.append(['?',name])
#remove it from the found list
del foundNames[foundNames.index(name)]
else:
#print "\t " + aName[len(aName)-1].lower() + " not in word corups"
assumtions.append("Aussuming " + name + " is a real name.")
#print "\tAussuming " + name + " is a real name."
if name not in foundNames:
foundNames.append(name)
namesNLP.append(name)
else:
assumtions.append("Aussuming " + name + " is a real name.")
#print "\tAussuming " + name + " is a real name."
if name not in foundNames:
foundNames.append(name)
namesNLP.append(name)
else:
namesMatched.append(name)
#lets try to do the opposit, see if there are any names in our name list that maches any text in the document, but have to clean up the doc
entire_file_clean = entire_file
entire_file_clean = re.sub('[0-9]+', '', entire_file_clean)
entire_file_clean = re.sub("\s\s+" , " ", entire_file_clean)
entire_file_clean = entire_file_clean.replace("\n",' ')
entire_file_clean = entire_file_clean.replace("\r",' ')
entire_file_clean = entire_file_clean.replace("'s",'')
entire_file_clean = entire_file_clean.translate(string.maketrans("",""), string.punctuation)
activeStep = activeStep + 1
updateProgress("Processing directory names",fileName,activeStep)
#print "Searching jazz directory names"
for name, uri in authorityNames.iteritems():
cleanName = name.translate(string.maketrans("",""), string.punctuation)
if name not in foundNames:
if ' ' + cleanName + ' ' in entire_file_clean:
if len(name.strip().split()) > 1:
#print "Found " + name.strip()
foundNames.append(name.strip())
#now we want to make sure that all the names are unique, not smaller part of larger name, this can happen if NLP gets a hit but not the full thing
#was caught
entire_semi_clean = entire_file
#not cleaning all punctutaiton here, so kind of verbose
entire_semi_clean = entire_semi_clean.replace("\n",' ')
entire_semi_clean = entire_semi_clean.replace("\r",' ')
entire_semi_clean = entire_semi_clean.replace("'s",' ')
entire_semi_clean = entire_semi_clean.replace(",",' ').replace(".",' ').replace("[",' ').replace("]",' ').replace("?",' ').replace("!",' ').replace("<",' ').replace(">",' ').replace("\"",' ').replace("'",' ').replace(")",' ').replace("(",' ')
#remove numbers
entire_semi_clean = re.sub('[0-9]+', '', entire_semi_clean)
#remove multiple spaces into one space
entire_semi_clean = re.sub("\s\s+" , " ", entire_semi_clean)
activeStep = activeStep + 1
updateProgress("Running regex name rules",fileName,activeStep)
tmp = []
for part in foundNames:
add = True
for full in foundNames:
if part in full and len(part) != len(full):
#print part, " looks like it is part of ", full
assumtions.append(part + " looks like it is part of " + full + " removing the part from name list")
add = False
part = part.replace(".",' ')
part = re.sub("\s\s+" , " ", part)
#now we also want to make sure that the name acutally exists as a possibly human readable format in the file
if " " + part + " " not in entire_semi_clean:
#print part, " does not look like it acutally exitst in the text file"
assumtions.append(part+" does not look like it acutally exitst in the text file, removing it from the name list")
add = False
if add:
tmp.append(part)
foundNames = list(tmp)
#a lot of transcripts will fill in partial names with something like [Jimmy] Carter, so look for that patern and replace them in the sentences
#and also add it to the names list
activeStep = activeStep + 1
updateProgress("Finding [sic] patterns",fileName,activeStep)
for aSent in allSentences:
regex = re.compile("([A-Z][a-z]*)\W\[([A-Z][a-z]*)\]")
r = regex.search(aSent)
if r:
#print r.groups(), aSent
aName = r.groups()[0] + ' ' + r.groups()[1]
aNameOld = r.groups()[0].strip() + ' [' + r.groups()[1].strip() +']'
#change it in this sentence
id = allSentences.index(aSent)
allSentences[id] = allSentences[id].replace(aNameOld,aName)
"""
#change it in all the partial matches as well
for partial in possiblePartials:
id = possiblePartials.index(partial)
if partial[1].find(aNameOld)!=-1:
#print "looking for", aNameOld
#print "before", possiblePartials[id][1]
possiblePartials[id][1] = possiblePartials[id][1].replace(aNameOld,aName)
#print "after", possiblePartials[id][1]
"""
if aName not in foundNames:
foundNames.append(aName)
for aSent in allSentences:
regex = re.compile("\[([A-Z][a-z]*)\]\W([A-Z][a-z]*)\W")
r = regex.search(aSent)
if r:
#print r.groups(), aSent
aName = r.groups()[0] + ' ' + r.groups()[1]
aNameOld = '['+ r.groups()[0].strip() + '] ' + r.groups()[1].strip()
id = allSentences.index(aSent)
allSentences[id] = allSentences[id].replace(aNameOld,aName)
"""
#print "looking for", aNameOld
for partial in possiblePartials:
if partial[1].find(aNameOld)!=-1:
id = possiblePartials.index(partial)
#print "before", possiblePartials[id][1]
possiblePartials[id][1] = possiblePartials[id][1].replace(aNameOld,aName)
#print "after", possiblePartials[id][1]
"""
if aName not in foundNames:
foundNames.append(aName)
#print foundNames,"\n\n"
activeStep = activeStep + 1
updateProgress("Running clean up rules",fileName,activeStep)
#######################################
#Clean up rules.
#######################################
for i in range(0,len(allSentences)):
##removes the hamilton line numbering
allSentences[i] = re.sub("\n[0-9]*\W" , "\n", allSentences[i])
allSentences[i] = re.sub(r'[0-9]*\s\s\s' , "", allSentences[i])
##remove the hamilton footer text
allSentences[i] = re.sub(r'\(c\) Hamilton College Jazz Archive-[0-9]*-\n','',allSentences[i])
allSentences[i] = re.sub(r'\(c\) Hamilton College Jazz Archive\s*-[0-9]*-\n','',allSentences[i])
#smithsonnian footer
allSentences[i] = re.sub(r'For additional information contact the Archives Center at 202.633.3270 or archivescenter@si.edu.*[0-9]*\n','',allSentences[i])
allSentences[i] = re.sub(r'For additional information contact the Archives Center at 202.633.3270 or archivescenter@si.edu','',allSentences[i])
#try to remove random page numbers that gett littered around
allSentences[i] = re.sub("\s[0-9]{2}\n" , "", allSentences[i])
#... need to put this into a interface eventually
allSentences[i] = re.sub(r'WILLIAMS.*[0-9]*\n','',allSentences[i])
allSentences[i] = re.sub(r'\sWILLIAMS\n','',allSentences[i])
#for i in range(0,len(possiblePartials)-1):
#possiblePartials[i][1] = re.sub("\n[0-9]*\W" , "\n", possiblePartials[i][1])
#possiblePartials[i][1] = re.sub(r'[0-9]*\s\s\s' , "", possiblePartials[i][1])
#store an orginal copy
allSentencesOrg = list(allSentences)
allSentencesHTML = list(allSentences)
#look at the >2 word names, make sure things did not bleed into eachother
for aName in list(foundNames):
if len(aName.split())>2:
if entire_file.find(aName) == -1:
shortName = ' '.join(aName.split()[0:len(aName.split())-1])
if entire_file.find(shortName) != -1:
#print "Could not find ", aName, 'but', shortName
assumtions.append(aName + ' is not a real name, but a mashup of two lines, the real name is ' + shortName)
del foundNames[foundNames.index(aName)]
foundNames.append(shortName)
activeStep = activeStep + 1
updateProgress("Finding nick name patterns",fileName,activeStep)
#a lot of musicans have the format First "Nickname" Last so see if we can match that pattern
for x in allSentences:
x = re.sub('[0-9]+', '', x)
x = re.sub("\s\s+" , " ", x)
x = x.replace("\n",' ')
x = x.replace("\r",' ')
x = x.replace("'s",'')
regex = re.compile('([A-Z][a-z]*)\W"([A-Z][a-z]*)"\W([A-Z][a-z]*)')
r = regex.search(x)
if r:
#add the vaious varations of their name to the found names
#full
aVaration = r.groups()[0] + ' ' + r.groups()[1] + ' ' + r.groups()[2]
if aVaration not in foundNames:
foundNames.append(aVaration)
#add to known sameAs
sameAs[aVaration] = r.groups()[0] + ' ' + r.groups()[2]
#first + last
aVaration = r.groups()[0] + ' ' + r.groups()[2]
if aVaration not in foundNames:
foundNames.append(aVaration)
#nick + last
aVaration = r.groups()[1] + ' ' + r.groups()[2]
if aVaration not in foundNames:
foundNames.append(aVaration)
#add to known sameAs
sameAs[aVaration] = r.groups()[0] + ' ' + r.groups()[2]
#nick name?
#aVaration = r.groups()[1]
#print aVaration
activeStep = activeStep + 1
updateProgress("Finding names based on first name patterns",fileName,activeStep)
#try to find any names that we did not match based on the first name file. Look for first names and see if it is a full name, and not in found names
for x in allSentences:
x = re.sub('[0-9]+', '', x)
x = re.sub("\s\s+" , " ", x)
x = x.replace("\n",' ')
x = x.replace("\r",' ')
x = x.replace("'s",'')
x = x.replace("[",' ').replace("]",' ')
#x = x.translate(string.maketrans("",""), string.punctuation)
for aFirstName in firstNamesFile:
aFirstName = aFirstName.title()