-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathraw_text_processing.py
executable file
·2422 lines (2176 loc) · 114 KB
/
raw_text_processing.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
# -*- coding: utf-8 -*-
###########################################################################
# Pre-processing raw text
# Date: November 2017
###########################################################################
import os
import re
import nltk # Natural Language toolkit
from nltk.tokenize import sent_tokenize, word_tokenize # form tokens from words/sentences
import matplotlib
matplotlib.use('Agg')
import string
import csv
from datetime import datetime
from collections import namedtuple, Counter
import itertools
from itertools import imap, permutations # set up namedtuple
from collections import defaultdict # create dictionary with empty list for values
import matplotlib.pyplot as plt # graphs
import networkx as nx
import numpy as np
########################################################################
## READING AND TOKENIZATION OF RAW TEXT (PRE-PROCESSING)
#TODO: move to a seperate file (up to readFile)
basic_pronouns = "I Me You She He Him It We Us They Them Myself Yourself Himself Herself Itself Themselves My your Her Its Our Their His"
possessive_pronouns = "mine yours his hers ours theirs my"
reflexive_pronouns = "myself yourself himself herself itself oneself ourselves yourselves themselves you've"
relative_pronouns = "that whic who whose whom where when"
neutral_pronouns = ['I', 'Me', 'You', 'It', 'We', 'Us', 'They', 'Them', 'Myself', 'Mine',
'Yourself', 'Itself', 'Themselves', 'My', 'Your', 'Its', 'Our', 'Their',
"One", "Ourselves", 'Yours']
female_pronouns = ['Her', 'Hers', 'Herself', "She", 'Herself']
male_pronouns = ['He', 'Him', 'His', 'Himself']
male_honorific_titles = ['M', 'Mr', 'Sir', 'Lord', 'Master', 'Gentleman',
'Sire', "Esq", "Father", "Brother", "Rev", "Reverend",
"Fr", "Pr", "Paster", "Br", "His", "Rabbi", "Imam",
"Sri", "Thiru", "Raj", "Son", "Monsieur", "M", "Baron",
"Prince", "King", "Emperor", "Grand Prince", "Grand Duke",
"Duke", "Sovereign Prince", "Count", "Viscount", "Crown Prince",
'Gentlemen', 'Uncle', 'Widower', 'Don', "Mistah", "Commodore",
"Grandfather", "Mister", "Brother-in-Law", "Mester", "Comrade", "Lordship"]
female_honorific_titles = ['Mrs', 'Ms', 'Miss', 'Lady', 'Mistress',
'Madam', "Ma'am", "Dame", "Mother", "Sister",
"Sr", "Her", "Kum", "Smt", "Ayah", "Daughter",
"Madame", "Mme", 'Madame', "Mademoiselle", "Mlle", "Baroness",
"Maid", "Empress", "Queen", "Archduchess", "Grand Princess",
"Princess", "Duchess", "Sovereign Princess", "Countess",
"Gentlewoman", 'Aunt', 'Widow', 'Doha', 'Comtesse', 'Baronne',
"Grandmother", "Sister-in-Law", "Missus"]
ignore_neutral_titles = ['Dr', 'Doctor', 'Captain', 'Capt',
'Professor', 'Prof', 'Hon', 'Honor', "Excellency",
"Honourable", "Honorable", "Chancellor", "Vice-Chancellor",
"President", "Vice-President", "Senator", "Prime", "Minster",
"Principal", "Warden", "Dean", "Regent", "Rector",
"Director", "Mayor", "Judge", "Cousin", 'Archbishop',
'General', 'Secretary', 'St', 'Saint', 'San', 'Assistant', "Director",
"The Right Honorable", "The Right Honourable", "Highness", "Cuz", "Poor",
"Silly", "Old"]
all_honorific_titles = male_honorific_titles + female_honorific_titles + ignore_neutral_titles
male_equ_titles = [['M', 'Mr', 'Mister', 'Mistah', 'Mester', 'Monsieur']]
female_equ_titles = [['Ms', 'Miss', 'Missus', 'Mademoiselle', 'Mlle'],
['Madam', "Ma'am", "Madame", "Mme"]]
neutral_equ_titles = [['Dr', 'Doctor'], ['Capt', 'Captain'],
['Professor', 'Prof'], ['St', 'Saint'],
["Cousin", "Cuz"]]
all_equal_titles = male_equ_titles + female_equ_titles + neutral_equ_titles
all_equal_titles = [item for sublist in all_equal_titles for item in sublist] # flat list of all titles for checking
potential_names_with_equal_titles = []
connecting_words = ["of", "the", "De", "de", "La", "la", 'al', 'y', 'Le', 'Las']
# WORDS TO IGNORE (parser has mislabeled)
words_to_ignore = ["Dear", "Chapter", "Volume", "Man", "O", "Anon", "Ought",
"Thou", "Thither", "Yo", "Till", "Ay", "Dearest", "Dearer", "Though",
"Hitherto", "Ahoy", "Alas", "Yo", "Chapter", "Again", "'D", "One", "'T",
"If", "thy", "Thy", "Thee", "Suppose", "There", "'There", "No-One", "Happily",
"Good-Night", "Good-Morning", 'To-Day', 'To-Morrow', "Compare", "Tis", "Good-Will",
'To-day', 'To-morrow', 'To-Night', 'Thine', 'Or', "D'You", "O'Er", "Aye", "Men"
"Ill", "Behold", "Beheld", "Nay", "Shall", "So-And-So", "Making-Up", "Ajar",
"Show", "Interpreting", "Then", "No", "Alright", "Tell", "Thereupon", "Yes",
"Abandon", "'But", "But", "'Twas", "Knelt", "Thou", "True", "False",
"Overhead", "Ware", "Fortnight", "Good-looking", "Something", "Grants", "Rescue",
"Head", "'Poor", "Tha'", "Tha'Rt", "Eh", "Whither", "Ah", "Sends",
"Silly", "Methought", "Come", "Dost", "Wilt", "Wherefore", "Doth", "Betwixt",
"Dat", "Midsummer", "Withal", "Thyself", "Shoots", "Came", "Sayeth",
"Aids", "Wilt", "Thou", "Whereupon", "Spake", "Poor", "Describe", "Opposite",
"Found", "Fish", "Woke", "Dim", "Alone", "Gwine", "`The", "O'Er", "Into", "mid-word"] # ignores noun instances of these word by themselves
#words_to_ignore += ["".join(a) for a in permutations(['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X'], 2)]
#words_to_ignore += ["".join(a) for a in ['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X', 'XV']]
numbers_as_words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five',
6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten',
11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen',
15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen',
19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty',
50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty',
90: 'Ninety', 0: 'Zero'}
total_numbers = numbers_as_words.values()
words_to_ignore += ["Chapter {0}".format("".join(a)) for a in []]
words_to_ignore += ["Chapter {0}".format("".join(a)) for a in permutations(['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X'], 2)]
words_to_ignore += ["Chapter {0}".format("".join(a)) for a in ['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X']]
words_to_ignore += ["Chapter {0}".format("".join(a)) for a in permutations(['1','2','3','4','5','6','7','8','9','10'], 2)]
words_to_ignore += ["Chapter {0}".format("".join(a)) for a in ['1','2','3','4','5','6','7','8','9','10']]
words_to_ignore += ["CHAPTER {0}".format("".join(a)) for a in permutations(['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X'], 2)]
words_to_ignore += ["CHAPTER {0}".format("".join(a)) for a in ['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X']]
words_to_ignore += ["Volume {0}".format("".join(a)) for a in permutations(['1','2','3','4','5','6','7','8','9','10'], 2)]
words_to_ignore += ["Volume {0}".format("".join(a)) for a in ['1','2','3','4','5','6','7','8','9','10']]
words_to_ignore += ["Volume {0}".format("".join(a)) for a in permutations(['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X'], 2)]
words_to_ignore += ["Volume {0}".format("".join(a)) for a in ['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X']]
words_to_ignore += ["VOLUME {0}".format("".join(a)) for a in permutations(['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X'], 2)]
words_to_ignore += ["VOLUME {0}".format("".join(a)) for a in ['I', 'II','III', 'IV', 'VI', 'XX', 'V', 'X']]
words_to_ignore += ["VOLUME {0}".format("".join(a)) for a in permutations(['1','2','3','4','5','6','7','8','9','10'], 2)]
words_to_ignore += ["VOLUME {0}".format("".join(a)) for a in ['1','2','3','4','5','6','7','8','9','10']]
def readFile(filename):
file_remove_extra = []
with open(filename, "r") as given_file:
string_words = given_file.read()
string_words = string_words.replace("\r\n\r\n", ".") # create sentences for chapter titles
string_words = string_words.replace("\n", " ")
string_words = string_words.replace("--", ", ")
string_words = string_words.replace("; ", ", ")
string_words = string_words.replace("*", "")
string_words = string_words.replace("_", "")
string_words = string_words.replace("!”", "!”.") # “Ah-h-h!” “How true!” “Amazing, amazing!” into sub-sentences (twain)
string_words = string_words.replace(".”", "”.") # splits the .". into two sentences at the end of a quote
string_words = string_words.replace("?”", "?”.") # splits ? into a sub-sentence
string_words = string_words.replace("—”", "”.") # splits dash into a sub-sentence
string_words = string_words.replace("'I", "' I") # fix puncutation where I
string_words = string_words.replace("'It", "' It")
string_words = string_words.replace("'we", "' we")
string_words = string_words.replace("'We", "' We")
string_words = string_words.replace("Mr.", "Mr") # period created breaks when spliting
string_words = string_words.replace("Ms.", "Ms")
string_words = string_words.replace("Mrs.", "Mrs")
string_words = string_words.replace("Dr.", "Dr")
string_words = string_words.replace("St.", "St")
# replace utf-8 elements
string_words = string_words.replace("’", "\'") # replace signal quotes
string_words = string_words.replace("“", "~\"") # isolate dialouge double quotes
string_words = string_words.replace("” ", "\"~")
string_words = re.sub(r'[\x90-\xff]', ' ', string_words, flags=re.IGNORECASE) # remove unicode (dash)
string_words = re.sub(r'[\x80-\xff]', '', string_words, flags=re.IGNORECASE) # remove unicode
file_remove_extra = string_words.split(' ')
file_remove_extra = filter(None, file_remove_extra) # remove empty strings from list
return file_remove_extra
def isDialogue(sentence):
# return true/false if the value is a quote
return '"' in sentence
def tokenizeSentence(string_sentence):
'''EXAMPLE
{60: 'After rather a long silence, the commander resumed the conversation.'}
'''
tokens_sentence_dict = {} # returns dict with {token location in text #: sentence}
tokens_sent = string_sentence.split('.')
index = 0
for t in range(len(tokens_sent)):
sent = tokens_sent[t].strip() # remove excess whitespace
for dia in sent.split('~'):
if dia != '': # store dialouge with its double quotes for identification
tokens_sentence_dict[index] = dia # {4: '"Oh, why can\'t you remain like this for ever!"'}
index += 1
t += 1
#print(tokens_sentence_dict)
return tokens_sentence_dict
def partsOfSpeech(token_dict):
'''EXAMPLE
60: ('After rather a long silence, the commander resumed the conversation.',
[('After', 'IN'), ('rather', 'RB'), ('a', 'DT'), ('long', 'JJ'), ('silence', 'NN'),
(',', ','), ('the', 'DT'), ('commander', 'NN'), ('resumed', 'VBD'), ('the', 'DT'),
('conversation', 'NN'), ('.', '.')])}
'''
from subprocess import check_output
import progressbar as pb
widgets = ['Running POS tagger: ', pb.Percentage(), ' ',
pb.Bar(marker=pb.RotatingMarker()), ' ', pb.ETA()]
timer = pb.ProgressBar(widgets=widgets, maxval=len(token_dict)).start()
for i in range(len(token_dict)):
timer.update(i)
no_punc = token_dict[i].translate(None, string.punctuation) # remove puncuation from part of speech tagging
pos_tagged = check_output(["./3_run_text.sh", token_dict[i]])
if "docker not running, required to run syntaxnet" not in pos_tagged:
pos_tagged = process_POS_conll(pos_tagged) # process conll output from shell
token_dict[i] = (token_dict[i], pos_tagged) # adds part of speech tag for each word in the sentence
else:
print("\n\tWARNING: docker not running, cannot run syntaxnet for POS, exiting")
exit()
timer.finish()
return token_dict
def process_POS_conll(conll_output):
'''
['1', 'At', '_', 'ADP', 'IN', '_', '13', 'prep', '_', '_']
['2', 'the', '_', 'DET', 'DT', '_', '3', 'det', '_', '_']
['3', 'period', '_', 'NOUN', 'NN', '_', '1', 'pobj', '_', '_']
['4', 'when', '_', 'ADV', 'WRB', '_', '7', 'advmod', '_', '_']
['5', 'these', '_', 'DET', 'DT', '_', '6', 'det', '_', '_']
['6', 'events', '_', 'NOUN', 'NNS', '_', '7', 'nsubj', '_', '_']
['7', 'took', '_', 'VERB', 'VBD', '_', '3', 'rcmod', '_', '_']
['8', 'place', '_', 'NOUN', 'NN', '_', '7', 'dobj', '_', '_']
'''
pos_processed = conll_output
#print(pos_processed)
start_data = 0
pos_processed = re.sub("\t", ",", pos_processed.strip())
pos_processed = re.sub(",", " ", pos_processed.strip())
pos_processed = pos_processed.splitlines()
for i in range(len(pos_processed)):
pos_processed[i] = pos_processed[i].split(" ")
#print(pos_processed[i])
return pos_processed
########################################################################
## GROUP PROPER NOUNS ENTITIES
def findProperNamedEntity(pos_dict):
# returns {sentence index: [list of all proper nouns grouped]
# {0: ["Scarlett O'Hara", 'Tarleton'], 1: ['Coast']}
pos_type_lst = []
# TODO: EXPAND PROPER NOUNS FOR COMMON WORDS AROUND WORD
previous_nnp_index = 0
for row, pos_named in pos_dict.iteritems():
if "NNP" in pos_named.XPOSTAG: #"NN" in pos_named.XPOSTAG or "POS" in pos_named.XPOSTAG or "IN" in pos_named.XPOSTAG or "DT" in pos_named.XPOSTAG:
pos_type_lst.append((int(pos_named.SENTENCE_INDEX), int(pos_named.ID), pos_named.FORM, int(pos_named.SENTENCE_LENGTH), pos_named.XPOSTAG))
previous_nnp_index = int(pos_named.ID)
if pos_named.FORM in connecting_words:
pos_type_lst.append((int(pos_named.SENTENCE_INDEX), int(pos_named.ID), pos_named.FORM, int(pos_named.SENTENCE_LENGTH), pos_named.XPOSTAG))
previous_nnp_index = int(pos_named.ID)
#if "the" in pos_named.FORM or "The" in pos_named.FORM:
# if previous_nnp_index < int(pos_named.ID): # only store of if it is part of an existing sentence
# pos_type_lst.append((int(pos_named.SENTENCE_INDEX), int(pos_named.ID), pos_named.FORM, int(pos_named.SENTENCE_LENGTH), pos_named.XPOSTAG))
#if "of" in pos_named.FORM:
# if previous_nnp_index < int(pos_named.ID): # only store of if it is part of an existing sentence
# pos_type_lst.append((int(pos_named.SENTENCE_INDEX), int(pos_named.ID), pos_named.FORM, int(pos_named.SENTENCE_LENGTH), pos_named.XPOSTAG))
total_sentence_indices = list(set([i[0] for i in pos_type_lst]))
sub_sentences = []
for index in total_sentence_indices:
# create sub sentences for each sentence [[0], [1])
sub_sentences.append([x for x in pos_type_lst if x[0] == index])
#print("\nsub_sentence={0}\n".format(sub_sentences))
from operator import itemgetter # find sequences of consecutive values
import itertools
grouped_nouns = {}
names_lst = []
sentence_index = []
for sentence in sub_sentences:
noun_index = [s_index[1] for s_index in sentence] # noun location in a sentence (index)
#print(sentence, noun_index)
consec_lst = []
for k, g in itertools.groupby(enumerate(noun_index), lambda x: x[1]-x[0]):
consec_order = list(map(itemgetter(1), g))
if len(consec_order) > 0: # if there is more than one noun in an order for a sentence
consec_lst.append(consec_order)
#consec_lst = [item for items in consec_lst for item in items]
for c_l in consec_lst:
g_name = [x for x in sentence if x[1] in c_l]
nnp_in_sentence = False
for i, v in enumerate(g_name):
nnp_in_sentence = "NNP" in v
if nnp_in_sentence: # if the nnp exist in the sub-list, exit and save
break
if nnp_in_sentence:
#print(c_l)
#print([x[2] for x in sentence if x[1] in c_l])
#print(" ".join([x[2] for x in sentence if x[1] in c_l]))
start_with_connecting_ignore = [x[2] for x in sentence if x[1] in c_l][0] in connecting_words
end_with_connecting_ignore = [x[2] for x in sentence if x[1] in c_l][-1] in connecting_words
if start_with_connecting_ignore or end_with_connecting_ignore:
# if the gne starts with a connecting word, ignore the connecting name: 'of Divine Providence' -> 'Divine Providence'
new_start_index = 0
for first_words in [x[2] for x in sentence if x[1] in c_l]:
if first_words not in connecting_words:
break # if it doesn't start with a connecting word, ignore
else:
new_start_index += 1
#print([x[2] for x in sentence if x[1] in c_l][new_start_index:])
#print(" ".join([x[2] for x in sentence if x[1] in c_l][new_start_index:]))
new_end_index = len([x[2] for x in sentence if x[1] in c_l]) # last element after it is been updated
for last_words in reversed([x[2] for x in sentence if x[1] in c_l]):
# if the gne ends with a connecting word, ignore the connecting name: 'Tom of the' -> 'Tom'
if last_words not in connecting_words:
break
else:
new_end_index -= 1
#if new_end_index < len([x[2] for x in sentence if x[1] in c_l]):
# print("original: {0}".format(" ".join([x[2] for x in sentence if x[1] in c_l])))
# print("update: {0}\n".format(" ".join([x[2] for x in sentence if x[1] in c_l][new_start_index:new_end_index])))
# print(new_start_index, new_end_index)
if (new_end_index != 0) and (new_start_index != len([x[2] for x in sentence if x[1] in c_l])): # if the entire gne wasn't connecting words
names_lst.append(" ".join([x[2] for x in sentence if x[1] in c_l][new_start_index:new_end_index]))
sentence_index.append(list(set([x[0] for x in sentence if x[1] in c_l][new_start_index:new_end_index]))[0])
else:
names_lst.append(" ".join([x[2] for x in sentence if x[1] in c_l]))
sentence_index.append(list(set([x[0] for x in sentence if x[1] in c_l]))[0])
dic_tmp = zip(sentence_index, names_lst)
grouped_nouns = defaultdict(list)
for s, n in dic_tmp:
grouped_nouns[s].append(n)
return dict(grouped_nouns)
def commonSurrouding(grouped_nouns_dict):
# find the most common preceding words to append
pass
def groupSimilarEntities(grouped_nouns_dict):
# filter out enities that only appear once and re-organize
'''
[['America'], ['Aronnax', 'Pierre', 'Pierre Aronnax'],
['Captain Farragut', 'Captain', 'Farragut'], ['Conseil'],
['English'], ['Europe'], ['French'], ['Gentlemen'], ['God'],
['Land', 'Mr Ned Land', 'Ned', 'Ned Land'], ['Latin'],
['Lincoln', 'Abraham', 'Abraham Lincoln'], ['Museum'],
['Natural'], ['OEdiphus'], ['Pacific'], ['Paris'], ['Professor'],
['Sir'], ['Sphinx'], ['United States', 'States', 'United'],
['sir']]
'''
#print("grouped_nouns_dict = {0}".format(grouped_nouns_dict))
counter_dict = dict(Counter([val for sublist in grouped_nouns_dict.values() for val in sublist]))
#print("counter={0}".format(counter_dict))
names_all = list(set([val for sublist in grouped_nouns_dict.values() for val in sublist])) # is a list of all unquie names in the list
compare_names_same_format = [val.upper() for val in names_all]
# loop through to group similar elements
gne_list_of_lists = grouped_nouns_dict.values()
gne_list_of_lists = list(set([item for sublist in gne_list_of_lists for item in sublist])) # creates a list of unquie names
import difflib
from difflib import SequenceMatcher
gne_name_group = []
# find most similar ['Professor', 'Professor Aronnax'], ['Aronnax', 'Mr Aronnax', 'Pierre Aronnax']
for gne in gne_list_of_lists:
for g in gne.split():
compared = difflib.get_close_matches(g, gne_list_of_lists)
if compared != []:
gne_name_group.append(compared)
subgrouping = []
#print("\ngne_list_of_lists: {0}".format(gne_list_of_lists))
if len(gne_list_of_lists) > 1: # if there is only one name in all the text (debugging short texts)
for gne in gne_list_of_lists:
sublist = []
if len(gne.split()) == 1 and len(gne.split()[0]) > 1: # includes only single instance values that are not a single letter
sublist.append(gne.split()) # include values that only appear once in a setence
for i in gne.split():
for gne_2 in gne_list_of_lists:
if i in gne_2 and i != gne_2 and (i != [] or gne_2 != []):
chapter_titles = ["CHAPTER", "Chapter", "Volume", "VOLUME"]
# only save words that don't include the chapter titles
found_in_i = any(val in chapter_titles for val in i.split())
found_in_gne2 = any(val in chapter_titles for val in gne_2.split())
if found_in_i or found_in_gne2:
# 'CHAPTER XXII Mr Rochester' -> 'Mr Rochester'
for title in chapter_titles:
if found_in_i:
#print(" ".join(i.split()[2:]))
i = " ".join(i.split()[2:])
break
if found_in_gne2:
#print(" ".join(gne_2.split()[2:]))
gne_2 = " ".join(gne_2.split()[2:])
break
if i != '' and gne_2 != '':
#print("FINAL APPEND={0}\n".format((i, gne_2)))
sublist.append([i, gne_2])
else:
if gne_2 != i:
if gne_2 not in i:
if [gne_2] not in sublist: # only keep one iteration of the name
if len(gne_2) > 1: # exclude single letter
sublist.append([gne_2])
subgrouping.append(sublist)
else:
subgrouping.append(gne_list_of_lists)
final_grouping = []
if len(subgrouping) > 1:
subgrouping = [x for x in subgrouping if x != []]
for subgroup in subgrouping:
final_grouping.append(list(set([item for sublist in subgroup for item in sublist])))
else:
final_grouping = subgrouping # keep the single element
iterate_list_num = list(range(len(final_grouping)))
for i in range(len(final_grouping)):
for num in iterate_list_num:
if num != i:
extend_val = list(set(final_grouping[i]).intersection(final_grouping[num]))
if extend_val:
final_grouping[i].extend(final_grouping[num])
final_grouping[i] = sorted(list(set(final_grouping[i]))) # extend list to include similar elements
#print("\nfinal_grouping: {0}".format(final_grouping))
final_grouping = sorted(final_grouping) # organize and sort
final_grouping = list(final_grouping for final_grouping,_ in itertools.groupby(final_grouping))
#final_grouping = [x for x in final_grouping if x != []] # remove empty lists
#print([item for item in final_grouping if item not in words_to_ignore])
count = 0
character_group_list = []
# remove any word that is part of the 'words_to_ignore' list or is a title by itself
for item in final_grouping:
sublist = []
for i in item:
#print("'{0}' to ignore = {1}".format(i, i in words_to_ignore or i.title() in all_honorific_titles))
if i in words_to_ignore or i.title() in all_honorific_titles:
count += 1
#print("in word to ignore = {0}".format(i))
else:
#print(i)
sublist.append(i)
#print("item = {0}".format(item))
if item[0] in words_to_ignore:
count += 1
if item[0] in words_to_ignore:
pass#print("in word to ignore = {0}".format(item[0]))
else:
#print(item[0])
sublist.append(item[0])
if sublist != []:
character_group_list.append(sublist)
#print("character_group_list: {0}".format(character_group_list))
character_group = [] # only save unquie lists
for i in character_group_list:
if i not in character_group:
character_group.append(i)
#print("\nfinal group: \n{0}".format(final_grouping))
#print("\ncharacter group: \n{0}".format(character_group))
#print(len([item for item in final_grouping if item not in words_to_ignore]))
#print(len(final_grouping))
#print(len(character_group))
#print("count = {0}".format(count))
return character_group
def lookupSubDictionary(shared_ent):
# return a dictionary of proper nouns and surrounding values for one-shot look up
'''
{"Scarlett O'Hara": ["O'Hara", 'Scarlett'], 'Tarleton': ['Tarleton'],
"O'Hara": ["Scarlett O'Hara", 'Scarlett'], 'Scarlett': ["Scarlett O'Hara", "O'Hara"],
'Coast': ['Coast']}
'''
sub_dictionary_lookup = defaultdict(list)
for group in shared_ent:
iterate_list_num = list(range(len(group)))
for i in range(len(group)):
for j in iterate_list_num:
if i != j:
sub_dictionary_lookup[group[i]].append(group[j])
if len(group) == 1:
sub_dictionary_lookup[group[i]].append(group[i]) # for single instances, store {'Tarleton':'Tarleton'{ as its own reference
return dict(sub_dictionary_lookup)
def mostCommonGNE(gne_grouped_dict):
# find the longest most common version of a name in gnes to become the global
#print("\nGlobal GNE")
#for key, value in gne_grouped_dict.iteritems():
# print(key, value)
#print(gne_grouped_dict.values())
pass
########################################################################
## INDEX PRONOUNS
def findPronouns(pos_dict):
# return the sentence index and pronouns for each sentence
#{0: ['he', 'himself', 'his'], 1: ['He', 'his', 'he', 'his', 'he', 'his']}
pos_type_lst = []
for row, pos_named in pos_dict.iteritems():
if "PRP" in pos_named.XPOSTAG:
pos_type_lst.append((int(pos_named.SENTENCE_INDEX), int(pos_named.ID), pos_named.FORM, int(pos_named.SENTENCE_LENGTH), pos_named.XPOSTAG))
total_sentence_indices = list(set([i[0] for i in pos_type_lst]))
sub_sentences = []
for index in total_sentence_indices:
# create sub sentences for each sentence [[0], [1])
sub_sentences.append([x for x in pos_type_lst if x[0] == index])
grouped_pronouns = {}
for pronoun_group in sub_sentences:
pronoun_lst = []
for pronoun in pronoun_group:
pronoun_lst.append(pronoun[2])
grouped_pronouns[pronoun[0]] = pronoun_lst
return grouped_pronouns
def coreferenceLabels(filename, csv_file, character_entities_dict, global_ent, pos_dict):
# save into csv for manual labelling
# TODO: set up with average paragraph length as size_sentences
size_sentences = 21000000000 # looking at x sentences at a time (could be automatically re-adjusted to fix max size of text)
# set to large number so it runs through all sentences (could be set to look at x number of sentences)
rows_of_csv_tuple = csv_file.values()
all_sentences_in_csv = list(set([int(word.SENTENCE_INDEX) for word in csv_file.values()]))
if size_sentences > max(all_sentences_in_csv)+1: # do not go out of range while creating sentences
size_sentences = max(all_sentences_in_csv)+1
print("Size of sentence for manual tagging = {0}".format(size_sentences))
# save chucks of text (size sentences = how many sentences in each chunk of text)
sub_sentences_to_tag = [all_sentences_in_csv[i:i + size_sentences] for i in xrange(0, len(all_sentences_in_csv), size_sentences)]
#print("character entities keys: {0}\n".format(character_entities_dict.keys()))
#print("\n")
row_dict = {} # to print data into csv
gne_index = 0 # display word of interst as [Name]_index
pronoun_index = 0 # display word of interst as [Pronoun]_index
for sentences_tag in sub_sentences_to_tag:
#print(sentences_tag)
# Test that csv is in order
#from itertools import groupby
#from operator import itemgetter
#for k, g in groupby(enumerate(sentences_tag), lambda (i, x): i-x):
# #print(len(map(itemgetter(1), g)))
# print(map(itemgetter(1), g))
# print("\n")
# #print(len(sentences_tag), size_sentences)
if len(sentences_tag) == size_sentences: # ignores sentences at the end that aren't the right length
sentences_in_order = ''
for i in range(sentences_tag[0], sentences_tag[-1]+1):
new_sentence_to_add = list(set([row.SENTENCE for row in rows_of_csv_tuple if row.SENTENCE_INDEX == str(i)]))[0]
if i+1 < sentences_tag[-1]+1:
next_sentence_check = list(set([row.SENTENCE for row in rows_of_csv_tuple if row.SENTENCE_INDEX == str(i+1)]))[0]
if len(next_sentence_check) == 1:
#print("old: {0}".format(new_sentence_to_add))
#print("NEXT IS NEARLY EMPTY, APPEND TO PREVIOUS SENTENCE: '{0}'".format(next_sentence_check))
new_sentence_to_add += next_sentence_check # add the final dialouge tag into the previous sentence
#print("new: {0}".format(new_sentence_to_add))
# returns a sentence in range
new_sentence_to_add = " {0} ".format(new_sentence_to_add) # add whitespace to the begining to find pronouns that start a sentence
if "," in new_sentence_to_add:
new_sentence_to_add = new_sentence_to_add.replace(",", " , ")
if "\"" in new_sentence_to_add:
new_sentence_to_add = new_sentence_to_add.replace("\"", " \" ")
# add space to identify pronouns/nouns at the end of a sentence
if "!" in new_sentence_to_add:
new_sentence_to_add = new_sentence_to_add.replace("!", " ! ")
if "?" in new_sentence_to_add:
new_sentence_to_add = new_sentence_to_add.replace("?", " ? ")
# tag pronouns first (from pos_dict)
if i in pos_dict.keys():
for pronoun in pos_dict[i]: # for all pronouns within the given sentence
total_found = re.findall(r'\b{0}\b'.format(pronoun), new_sentence_to_add)
if re.search(r' \b{0}\b '.format(pronoun), new_sentence_to_add): # match full word
for tf in range(len(total_found)):
new_sentence_to_add = new_sentence_to_add.replace(" {0} ".format(pronoun), " <{0}>_p{1} ".format(pronoun, pronoun_index), tf+1)
pronoun_index += 1
# tag proper nouns
found_longest_match = ''
gne_found_in_sentence = False # if found, print and update the sentence value
lst_gne = []
lst_gne = [gne_name for gne_name in character_entities_dict.keys() if gne_name in new_sentence_to_add]
lst_gne = [x for x in lst_gne if x != []]
index_range_list = [] # compare each index values
all_index_values = [] # contains all index values of gnes
to_remove = [] # if a value is encompassed, it should be removed
if len(lst_gne) > 0:
#print("\nlst_gne = {0}".format(lst_gne))
for gne in lst_gne: # create the index values for each enitity
#print("'{0}' in {1}".format(gne, new_sentence_to_add))
search_item = re.search(r"\b{0}\b".format(gne), new_sentence_to_add)
if not search_item: # if it return none
break # skip item if not found
else:
start = search_item.start() # store the start index of the gne
end = search_item.end() # store the end index of the gne
index_range_word = [start, end]
all_index_values.append(index_range_word)
if len(index_range_list) == 0: # useful for debugging
#print("FIRST GNE {0} has index {1}".format(gne, index_range_word))
pass
else:
for range_index in index_range_list: # the index of the value is stored and new words are check to see if they are contained wtihing
# example: united is within 'united states'
if len(lst_gne) > 1:
if (range_index[0] == index_range_word[0]) and (index_range_word[1] == range_index[1]):
pass
else:
if (range_index[0] <= index_range_word[0]) and (index_range_word[1] <= range_index[1]):
#print("{0} <= {1}-{2} <= {3}".format(range_index[0], index_range_word[0], index_range_word[1], range_index[1]))
#print("{0} IS CONTAINED BY GNE = {1}\n".format(gne, new_sentence_to_add[range_index[0]:range_index[1]]))
to_remove.append(index_range_word)
if (index_range_word[0] <= range_index[0]) and(index_range_word[1] >= range_index[1]):
#pass # reprsents the larger word that encompassing the smaller word
#print("{0} <= {1}-{2} <= {3}".format(index_range_word[0], range_index[0],range_index[1], index_range_word[1]))
#print("{0} IS EMCOMPASSED BY GNE = {1}\n".format(gne, new_sentence_to_add[index_range_word[0]:index_range_word[1]]))
to_remove.append(range_index)
#print("{0} <= {1} = {2}".format(index_range_word[0], range_index[0], index_range_word[0] <= range_index[0]))
#print("{0} >= {1} = {2}".format(index_range_word[1], range_index[1], index_range_word[1] >= range_index[1]))
index_range_list.append(index_range_word)
#print("remove index values = {0}".format(to_remove))
#print("largest gne index values ALL = {0}".format(all_index_values))
all_index_values = sorted([x for x in all_index_values if x not in to_remove]) # index in order based on start value
#print("shared (with removed encompassed) = {0}".format(all_index_values)) # remove all encompassed elements
updated_index = []
new_characters_from_update = 0 # new characters to keep track of character length when indexing
repeats_to_find = []
for counter, index_val in enumerate(all_index_values):
if counter > 0:
new_characters_from_update = len("<>_n ")*counter
start_word = index_val[0] + new_characters_from_update
end_word = index_val[1] + new_characters_from_update
updated_index.append([start_word, end_word])
find_repeats = new_sentence_to_add[start_word:end_word]
repeats_to_find.append(find_repeats)
replacement_string = "<{0}>_n ".format(new_sentence_to_add[start_word:end_word])
new_sentence_to_add = "".join((new_sentence_to_add[:start_word], replacement_string, new_sentence_to_add[end_word:]))
sub_counter = counter
# add repeated gne values
# if the same name appears more than once in a sentence
sub_counter = 0
new_characters_from_update = 0 # new characters to keep track of character length when indexing
for find_additional in repeats_to_find:
repeat_item = re.finditer(r"\b{0}\b".format(find_additional), new_sentence_to_add)
for m in repeat_item:
index_to_check = [m.start(), m.end()]
if [m.start()-1,m.end()-1] not in updated_index: # check that name hasn't been already assigned
if new_sentence_to_add[m.start()-1] != '<' and new_sentence_to_add[m.end():m.end()+3] != '>_n':
start_word = m.start() + new_characters_from_update
end_word = m.end() + new_characters_from_update
replacement_string = "<{0}>_n ".format(new_sentence_to_add[start_word:end_word])
new_sentence_to_add = "".join((new_sentence_to_add[:start_word], replacement_string, new_sentence_to_add[end_word:]))
sub_counter += 1
new_sent = new_sentence_to_add.split()
# label all proper nouns with an associated index value for noun
for index, word_string in enumerate(new_sent):
if '>_n' in word_string:
if word_string != ">_n":
new_sent[index] = '{0}{1}'.format(word_string, gne_index)
new_sentence_to_add = " ".join(new_sent)
gne_index += 1
new_sentence_to_add = new_sentence_to_add.strip() # remove precending whitespace
new_sentence_to_add = new_sentence_to_add.replace('" ', '"') # edit the speech puncutations
new_sentence_to_add = new_sentence_to_add.replace(' "', '"') # edit the speech puncutations
new_sentence_to_add = new_sentence_to_add.replace('\' ', '\'') # edit the speech puncutations
new_sentence_to_add = new_sentence_to_add.replace(' , ', ', ') # edit the speech puncutations
new_sentence_to_add = new_sentence_to_add.replace(' ! ', '! ') # edit the speech puncutations
new_sentence_to_add = new_sentence_to_add.replace(' ? ', '? ') # edit the speech puncutations
if new_sentence_to_add != '"': # if the value is just the end of a dialouge tag (already included, ignore)
sentences_in_order += new_sentence_to_add + '. '
#print(new_sentence_to_add + '. ')
#print("\nFinal Sentence Format:\n\n{0}".format(sentences_in_order))
saveTagforManualAccuracy(sentences_in_order)
else:
# determine that no sentences are skipped because of csv error
print("Manual Accuracy Tag not created, len(sentences_tag) must equal size_sentences")
exit()
def saveTagforManualAccuracy(sentences_in_order):
## corefernece will call the csv creator for each 'paragraph' of text
given_file = os.path.basename(os.path.splitext(filename)[0]) # return only the filename and not the extension
output_filename = "manualTagging_{0}.csv".format(given_file.upper())
fieldnames = ['FILENAME', 'TEXT',
'FOUND_PROPER_NOUN', 'MISSED_PROPER_NOUN',
'FOUND_PRONOUN', 'MISSED_PRONOUN']
split_sentences_in_list = [e+'.' for e in sentences_in_order.split('.') if e] # split sentence based on periods
split_sentences_in_list.remove(' .') # remove empty sentences
sentence_size = 1 # size of the sentence/paragraph saved in manual tagging (one line for one sentence)
sentence_range = [split_sentences_in_list[i:i+sentence_size] for i in xrange(0, len(split_sentences_in_list), sentence_size)]
# range stores the sentences in list of list based on the size of tag
#print("\n")
#for sentence_tag in sentence_range:
# print(''.join(sentence_tag))
# print(''.join(sentence_tag).count("]_n"))
# print(''.join(sentence_tag).count("]_p"))
# print("\n")
print("opening manual tag: {0}".format('manual_tagging/{0}'.format(output_filename)))
with open('manual_tagging/{0}'.format(output_filename), 'w') as tag_data:
writer = csv.DictWriter(tag_data, fieldnames=fieldnames)
writer.writeheader()
# leave MISSED empty for manual tagging
for sentence_tag in sentence_range:
writer.writerow({'FILENAME': os.path.basename(os.path.splitext(filename)[0]),
'TEXT': ''.join(sentence_tag),
'FOUND_PROPER_NOUN': ''.join(sentence_tag).count(">_n"),
'MISSED_PROPER_NOUN': None,
'FOUND_PRONOUN': ''.join(sentence_tag).count(">_p"),
'MISSED_PRONOUN': None
})
print("{0} create MANUAL TAGGING for CSV".format(output_filename))
def breakTextPandN(manual_tag_dir, loaded_gender_model):
# resolve gender and pronoun noun interactions (resolution)
pronoun_noun_dict = {}
given_file = os.path.basename(os.path.splitext(filename)[0]) # return only the filename and not the extension
# set up dict for pronouns and gender: {'His': 'Male', etc...}
pronoun_gender = {f: 'Female' for f in female_pronouns}
m_pronoun_gender = {m: 'Male' for m in male_pronouns}
pronoun_gender.update(m_pronoun_gender)
n_pronoun_gender = {n: 'Neutral' for n in neutral_pronouns}
pronoun_gender.update(n_pronoun_gender)
#check that all pronouns have been included in the dictionary
test_full_list = female_pronouns + male_pronouns + neutral_pronouns
for i in test_full_list:
if i not in pronoun_gender:
print("'{0}' NOT FOUND IN GENDER DICT".format(i))
tagged_text = [] # store old rows
with open(manual_tag_dir, 'r') as tag_data:
reader = csv.reader(tag_data)
next(reader) # skip header
for row in reader:
tagged_text.append(row[1]) # store the sentence in order
sub_dict_titles = ['full_text', 'found_all_brackets', 'found_proper_name_value',
'found_proper_name_index', 'found_pronoun_value', 'found_pronoun_index']
line_by_line_dict = {}
pronoun_noun_dict = {f: [] for f in sub_dict_titles}
total_sentences_to_check_behind = 3 # TODO: update with pronouns average information
#print("\n")
for line_num, full_text in enumerate(tagged_text):
#print(full_text)
pronoun_noun_dict['full_text'].append([full_text])
find_gne_in_sentence_pattern = r'(?<=\<)(.*?)(?=\>)'
found_all_brackets = re.findall(find_gne_in_sentence_pattern, full_text) # everything together in the order that they appear
pronoun_noun_dict['found_all_brackets'].append([found_all_brackets])
#print('\n')
#print(found_all_brackets)
all_found_name_index = [[m.start(), m.end()] for m in re.finditer(find_gne_in_sentence_pattern, full_text)] # get index of all matches
found_proper_name_value = [full_text[i[0]:i[1]] for i in all_found_name_index if full_text[i[1]+2] is 'n'] # store named ents
found_proper_name_index = [i for i in all_found_name_index if full_text[i[1]+2] is 'n'] # store named index of names
#for index_g in all_found_name_index:
# print(full_text[index_g[0]:index_g[1]])
pronoun_noun_dict['found_proper_name_value'].extend([found_proper_name_value])
pronoun_noun_dict['found_proper_name_index'].extend([found_proper_name_index])
found_pronoun_value = [full_text[i[0]:i[1]] for i in all_found_name_index if full_text[i[1]+2] is 'p'] # store pronouns seperately
found_pronoun_index = [i for i in all_found_name_index if full_text[i[1]+2] is 'p'] # store named index of pronouns
pronoun_noun_dict['found_pronoun_value'].extend([found_pronoun_value])
pronoun_noun_dict['found_pronoun_index'].extend([found_pronoun_index])
# store in a sub-dictionary for each line
line_by_line_dict[line_num] = {'full_text': full_text.strip(),
'found_all_brackets': found_all_brackets,
'found_proper_name_value': found_proper_name_value,
'found_proper_name_index': found_proper_name_index,
'found_pronoun_value': found_pronoun_value,
'found_pronoun_index': found_pronoun_index }
#print("\nfound pronouns index: {0}".format(all_found_name_index))
#for index_g in all_found_name_index:
# print(full_text[index_g[0]:index_g[1]])
#print('\n')
#print(found_proper_name_value)
#for given_name in found_proper_name_value:
# print("{0} is {1}".format(given_name, gender_gne_tree[given_name]))
#print('\n')
#print(found_pronoun_value)
#for pron in found_pronoun_value:
#print("{0} is {1}".format(pron, pronoun_gender[pron.capitalize()]))
# compress dictionray from a list of list to a single list
for key, value in pronoun_noun_dict.iteritems():
pronoun_noun_dict[key] = [item for sublist in value for item in sublist]
if key == 'full_text':
pronoun_noun_dict[key] = [''.join(pronoun_noun_dict[key])] # join the sentences into a single sentence
return pronoun_noun_dict, line_by_line_dict
def determineGenderOfListOfNames(loaded_gender_model, list_of_names):
# use trained model to determine liekly gender of a name and the sub-names to find max likelyhood
#print("DETERMINE GENDER OF: {0}".format(list_of_names))
most_likely_gender_label = [] # label and prob: ['Male', (Female: 0.28571, Male: 0.71429)]
determine_words_to_weight_less = []
female_prob = 0.0
male_prob = 0.0
for full_name in list_of_names:
if bool(re.search(r'\d', full_name)): # if incorrectly labeled a number
# number, give a default tag Male since numbres can't be checked for value
gender_is = 'Male'
else:
found_with_title = False
#print(full_name)
full_name_in_parts = full_name.split(" ")
#print(full_name_in_parts)
if bool(set(full_name_in_parts) & set(connecting_words)): #if connecting words in name
found_connecting_ignore_following = False
for part in full_name_in_parts:
if part in connecting_words:
found_connecting_ignore_following = True
determine_words_to_weight_less.append(part)
if found_connecting_ignore_following and part not in connecting_words: # if word that following connecting word
determine_words_to_weight_less.append(part)
# weight of and the less, but also 'Queen Elizabeth of England', weigh 'of England' less
#print("words to weigh less = {0}".format(determine_words_to_weight_less))
# if name is part of a gendered honorific, return: Mr Anything is a male
if full_name_in_parts[0].title() in male_honorific_titles:
#print("'{0}' contains '{1}' found: Male".format(full_name, full_name_in_parts[0]))
gender_is = 'Male'
male_prob += 1.0
found_with_title = True
if full_name_in_parts[0].title() in female_honorific_titles:
#print("'{0}' contains '{1}' found: Female".format(full_name, full_name_in_parts[0]))
gender_is = 'Female'
female_prob += 1.0
found_with_title = True
# find the name for each part of the name, choose highest
#print("'{0}' not found, calculating a probability...".format(full_name)) # not found in gendered honorifics
# run test on each part of the name, return the largest so that last names don't overly effect
dt = np.vectorize(DT_features) #vectorize dt_features function
weight_last_name_less = 0.3
weight_connecting_words_less = 0.2 # weight words that follow 'of' less
if not found_with_title:
for sub_name in full_name_in_parts:
# determine if the name is likely to be the last name, if so, weight less than other parts of the name
if sub_name in connecting_words:
# do not calculate for titles "Queen of England" shouldn't find for England
break
else:
if sub_name not in ignore_neutral_titles:
# female [0], male [1]
load_prob = loaded_gender_model.predict_proba(dt([sub_name.title()]))[0]
if sub_name in determine_words_to_weight_less:
#print("this should be weighted less = '{0}'".format(sub_name))
load_prob = load_prob*weight_connecting_words_less
else: # if not in connecting words, check if last name
is_a_last_name = isLastName(gne_tree, sub_name)
#print("\tprobability: {0}\n".format(load_prob))
if is_a_last_name: # if last name, weigh less than other names
#print("'{0}' is a last name, will weight less".format(sub_name))
load_prob = load_prob*weight_last_name_less
female_prob += load_prob[0]
male_prob += load_prob[1]
#print("\t updated: f={0}, m={1}".format(female_prob, male_prob))
#if (abs(male_prob - female_prob) < 0.02): #within 2 percent, undeterminex
# gender_is = "UNDETERMINED"
#else:
gender_is = 'Male' if male_prob > female_prob else 'Female'
#print("The subname '{0}' is most likely {1}\nFemale: {2:.5f}, Male: {3:.5f}".format(full_name, gender_is, female_prob, male_prob))
#print("\tFINAL: The list '{0}' is most likely {1}\n\tFemale: {2:.5f}, Male: {3:.5f}\n".format(list_of_names, gender_is, female_prob, male_prob))
return gender_is
def determineGenderNameDict(loaded_gender_model, gne_tree):
# use trained model to determine the likely gender of a name
gender_gne = {}
all_gne_values = gne_tree.keys()
for key, values in gne_tree.iteritems():
for k, v in values.iteritems():
# add all sub_trees to list
all_gne_values += [k]
all_gne_values += v
all_gne_values = [[x] for x in all_gne_values] # covert each element to a list to use generic gender determine function
for full_name in all_gne_values:
gender_is = determineGenderOfListOfNames(loaded_gender_model, full_name)
gender_gne[full_name[0]] = gender_is
return gender_gne
def isLastName(gne_tree, sub_name):
# determine if the name is likely to be the last name
#{'Samsa': ['Samsa'], 'Gregor': ['Gregor', 'Gregor Samsa']}
# last name is the most common last element in a name and has no futher sub-roots
# last name will be weighted less, if there are other elements present
is_last_name = False
for key, value in gne_tree.iteritems():
if sub_name in key:
if sub_name in key.split()[-1] and len(value) > 1: # if in the last position and isn't the only value {'John': ['John']}
is_last_name = True
#print("'{0}' is a last name = {1}".format(sub_name, is_last_name))
return is_last_name
def loadDTModel():
# load saved gender model from gender_name_tagger
from sklearn.externals import joblib # save model to load
model_file_dir = 'gender_name_tagger'
updated_saved_model = [f for f in os.listdir(model_file_dir) if 'pipeline_gender_saved_model' in f][0]
print("LOADING SAVED GENDER NAME MODEL: {0}".format(updated_saved_model))
pipeline_loaded = joblib.load('{0}/{1}'.format(model_file_dir, updated_saved_model))
return pipeline_loaded
def DT_features(given_name):
test_given_name = ['corette', 'corey', 'cori', 'corinne', 'william', 'mason', 'jacob', 'zorro'] #small test
FEATURE_TAGS = ['first_letter',
'first_2_letters',
'first_half',
'last_half',
'last_2_letters',
'last_letter',
'length_of_name']
features_list = []
name_features = [given_name[0], given_name[:2], given_name[:len(given_name)/2], given_name[len(given_name)/2:], given_name[-2:], given_name[-1:], len(given_name)]
#[['z', 'zo', 'zo', 'rro', 'ro', 'o', 5], ['z', 'zo', 'zo', 'rro', 'ro', 'o', 5]]
features_list = dict(zip(FEATURE_TAGS, name_features))
return features_list
def gneHierarchy(character_entities_group, over_correct_for_multiple_title):
# merge gne into a dict for look up
'''
key: Dr Urbino
{'Dr': [['Dr', 'Dr Juvenal Urbino', 'Dr Urbino'], ['Urbino']],
'Urbino': [['Dr', 'Dr Juvenal Urbino', 'Dr Urbino'], ['Urbino']]}
'''
# if there are a name with a different version of the title, include both
if over_correct_for_multiple_title:
character_entities_group, found_similar = addNameWithSameTitle(character_entities_group) # add names with different titles
character_split_group = [x.split() for x in character_entities_group]
character_split_group = sorted(character_split_group, key=len, reverse=True)
gne_tree = defaultdict(dict)
gne_dict_sub = {}
for longer_name in character_split_group:
#print("{0} IS NOT in gne_tree: {1}".format(" ".join(longer_name), gne_tree))
#print("longer: {0}".format(longer_name))
already_in_tree = any(" ".join(longer_name) in g for g in gne_tree)
if not already_in_tree: # if not already in a sub tree
if len(longer_name) > 1 or len(longer_name[0]) > 1: # ignore intials 'C'
#print("base: {0}".format(longer_name))
#print("base: {0}".format(" ".join(longer_name)))
for sub_long_name in longer_name:
gne_tree_word_tree = []
#print("sub: {0}".format(sub_long_name))
gne_tree_word_tree.append(sub_long_name)
for smaller_name in character_entities_group:
name_with_caps = sub_long_name
is_sub_capitalized = sub_long_name.isupper()
if is_sub_capitalized:
name_with_caps = sub_long_name.title()
if name_with_caps in smaller_name.split() and name_with_caps not in connecting_words:
# store only honorific titles that include elements of the same name
# 'Dr Juvenal Urbino' NOT 'Dr Lacides Olivella', but 'Dr Juvenal Urbino' and 'Dr Urbino'
if name_with_caps in all_honorific_titles and len(longer_name) > 1:
if any(i.title() in longer_name for i in smaller_name.split() if i.title() not in all_honorific_titles):
#print("\t\tindex: {0}".format(smaller_name.split().index(sub_long_name.title())))
sub_name_join = " ".join(smaller_name.split()[smaller_name.split().index(sub_long_name.title()):])
#print("\t\t\n\n\nnewfound: {0}".format(sub_name_join))
#print("sub_name_join.title() not in gne_tree_word_tree = {0}".format(sub_name_join.title() not in gne_tree_word_tree))
if sub_name_join.title() not in gne_tree_word_tree:
gne_tree_word_tree.append(sub_name_join)
if over_correct_for_multiple_title:
# add other versions of the same name: "Capt Nemo" and "Captian Nemo"
for potential_conflict in found_similar:
#print("sub_name_join in potential_conflict = {0}".format(sub_name_join in potential_conflict))
if sub_name_join in potential_conflict:
for other_name in potential_conflict:
if other_name != sub_name_join:
if len(other_name.split()) > 1:
sub_name_first_name = sub_name_join.split()[1]
sub_name_last_name = sub_name_join.split()[-1]
other_name_first_name = other_name.split()[1]
other_name_last_name = other_name.split()[-1]
if sub_name_first_name == other_name_first_name or other_name_last_name == sub_name_last_name:
#print("current = {0}".format(sub_name_join))