-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGutenTag.py
6259 lines (5331 loc) · 272 KB
/
GutenTag.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 -*-
version = "0.1.5"
standalone = False
online = False
online_max_texts = 500
http_port = 8000
import sys
if len(sys.argv) > 1 and sys.argv[1] == "-c":
config_mode = True
else:
config_mode = False
if standalone:
sys.frozen = True
my_path = sys.executable
if "/" in my_path:
my_path = my_path[:my_path.rfind("/") + 1]
else:
my_path = my_path[:my_path.rfind("\\") + 1]
if 'posix' in sys.builtin_module_names:
import posix
posix.chdir(my_path)
else:
import os
my_path = os.getcwd() + "/"
sys.path.insert(0, my_path + "Lib")
import zipfile
import cPickle
import time
import gc
import os
import codecs
import re
import copy
import encodings
import io
import math
import operator
import StringIO
import random
import webbrowser
from collections import defaultdict,Counter
import SocketServer
import socket
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urllib import unquote,quote
from multiprocessing import cpu_count,Queue,Process,Lock,freeze_support
from nltk.tokenize import regexp
if online:
import urllib2
from threading import Thread
import json
gc.disable()
re.DOTALL = True
def has_capital(word):
return any([letter.isupper() for letter in word])
def alpha_count(word):
count = 0
for i in range(len(word)):
if word[i].isalpha():
count += 1
return count
romanNumeralMap = (('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1))
#Define pattern to detect valid Roman numerals
'''
romanNumeralPattern = re.compile("""
^ # beginning of string
M{0,4} # thousands - 0 to 4 M's
(CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
# or 500-800 (D, followed by 0 to 3 C's)
(XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
# or 50-80 (L, followed by 0 to 3 X's)
(IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
# or 5-8 (V, followed by 0 to 3 I's)
$ # end of string
""" ,re.VERBOSE)
'''
romanNumeralPattern = re.compile("""
^ # beginning of string
(XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
# or 50-80 (L, followed by 0 to 3 X's)
(IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
# or 5-8 (V, followed by 0 to 3 I's)
$ # end of string
""" ,re.VERBOSE)
def is_roman(string):
return romanNumeralPattern.search(string)
def convert_roman(string):
result = 0
index = 0
for numeral, integer in romanNumeralMap:
while string[index:index+len(numeral)] == numeral:
result += integer
index += len(numeral)
return result
def fix_year(year_string):
year_string = year_string.replace("?", "")
year_string = year_string.replace("AD", "")
if "BC" in year_string:
BC = True
year_string = year_string.replace("BC"," ")
else:
BC = False
try:
year = int(year_string)
if BC:
year = -year
except:
year = "?"
return year
# This class deals with functions for reading Project Gutenberg metadata
class MetadataReader:
wanted_tags = set(["Author","Title", "LoC Class", "Subject", "Language"])
def get_metatag_contents(self,html,tag):
index = html.find('<th scope="row">%s</th>' % tag)
result = []
while index != -1:
result.append(html[html.find("<td>",index) + 4 :html.find("</td>", index)].replace("&","&"))
index = html.find('<th scope="row">%s</th>' % tag, index + 1)
return result
def expand_author(self,tags):
if "Author" not in tags:
return
authors = tags["Author"]
tags["Author"] = []
tags["Author Birth"] = []
tags["Author Death"] = []
tags["Author Given"] = []
tags["Author Surname"] = []
for author in authors:
parts = author.split(", ")
birth = None
death = None
given = None
surname = None
if len(parts) >= 2:
if parts[-1].count("-") == 1:
birth_string, death_string = parts[-1].split("-")
birth = fix_year(birth_string)
death = fix_year(death_string)
parts = parts[:-1]
parts.reverse()
author = " ".join(parts)
if len(parts) == 2:
given = parts[0]
surname = parts[1]
found_names = True
if given:
tags["Author Given"].append(given)
else:
tags["Author Given"].append("?")
if surname:
tags["Author Surname"].append(surname)
else:
tags["Author Surname"].append("?")
if birth:
tags["Author Birth"].append(birth)
else:
tags["Author Birth"].append("?")
if death:
tags["Author Death"].append(death)
else:
tags["Author Death"].append("?")
tags["Author"].append(author)
def get_href_and_charset(self,html_text):
index = html_text.find("text/plain")
if index == -1:
return None,-1
index = html_text.find('charset="', index)
if index == -1:
charset = "utf-8"
index = html_text.find("text/plain")
else:
charset = html_text[index + 9:html_text.find('"',index + 9)]
index = html_text.find(' href="', index)
if index == -1:
href = None
else:
href = html_text[index + 9:html_text.find('"',index + 9)]
return href, charset
def get_PG_metadata(self,filename):
f = codecs.open(filename, encoding="utf-8")
html_text = f.read()
f.close()
tag_dict = {}
for tag in self.wanted_tags:
tag_dict[tag] = self.get_metatag_contents(html_text,tag)
self.expand_author(tag_dict)
for i in range(len(tag_dict["Title"])):
tag_dict["Title"][i] = tag_dict["Title"][i].replace("\n","\t")
href, charset = self.get_href_and_charset(html_text)
return href,charset,tag_dict
class MetadataReaderRDF:
title_remove = [" "]
language_lookup = {"en":"English","fr":"French","es":"Spanish","de":"German","pt":"Portuguese","ja":"Japanese","zh":"Chinese","ru":"Russian","ar":"Arabic","pl":"Polish","it":"Italian","el":"Greek","he":"Hebrew","ko":"Korean","hi":"Hindi","la":"Latin","nl":"Dutch","sv":"Swedish","no":"Norweigan","fi":"Finnish"}
def get_PG_metadata(self,filename):
f = codecs.open(filename, encoding="utf-8")
tag_dict = defaultdict(list)
in_subject = False
in_creator = False
add_next_line_to_title = False
encodings = []
for line in f:
if add_next_line_to_title:
if "<" in line:
end_index = line.find("<")
add_next_line_to_title = False
else:
end_index = -1
tag_dict["Title"][-1] += "\t" + line[:end_index]
if "<dcterms:creator>" in line:
in_creator = True
full_name = None
birth_year = None
death_year = None
first_name = None
last_name = None
elif "</dcterms:creator>" in line:
if full_name:
tag_dict["Author"].append(full_name)
tag_dict["Author Birth"].append(birth_year)
tag_dict["Author Death"].append(death_year)
tag_dict["Author Given"].append(first_name)
tag_dict["Author Surname"].append(last_name)
elif in_creator and "<pgterms:name>" in line:
start_index = line.find(">") + 1
end_index = line.find("<",start_index)
name = line[start_index:end_index]
#if "(" in name:
# name = name[:name.find(" (")]
stuff = name.split(', ')
if len(stuff) == 2:
first_name = stuff[1]
last_name = stuff[0]
stuff.reverse()
full_name = " ".join(stuff)
#print full_name
elif in_creator and "pgterms:birthdate" in line:
start_index = line.find(">") + 1
end_index = line.find("<",start_index)
birth_year = line[start_index:end_index]
birth_year = fix_year(birth_year)
elif in_creator and "pgterms:deathdate" in line:
start_index = line.find(">") + 1
end_index = line.find("<",start_index)
death_year = line[start_index:end_index]
death_year = fix_year(death_year)
elif "<dcterms:subject>" in line:
in_subject = True
value = None
is_LLC = False
elif "</dcterms:subject>" in line:
in_subject = False
if value:
if is_LLC:
tag_dict["LoC Class"].append(value)
else:
tag_dict["Subject"].append(value)
elif in_subject and "<rdf:value>" in line:
start_index = line.find(">") + 1
end_index = line.find("<",start_index)
value = line[start_index:end_index]
elif in_subject and '<dcam:memberOf rdf:resource="http://purl.org/dc/terms/LCC"/>' in line:
is_LLC = True
elif "<pgterms:file" in line and ".txt" in line:
if "-8" in line:
encodings.append("latin-1")
elif "-0" in line:
encodings.append("utf-8")
else:
encodings.append("us-ascii")
elif "<dcterms:title>" in line:
start_index = line.find(">") + 1
end_index = line.find("<",start_index)
if end_index == -1:
add_next_line_to_title = True
tag_dict["Title"].append(line[start_index:end_index])
elif "RFC4646" in line:
start_index = line.find(">") + 1
lang = line[start_index:start_index + 2]
if lang in self.language_lookup:
tag_dict["Language"].append(self.language_lookup[lang])
else:
tag_dict["Language"].append("Other")
f.close()
if "us-ascii" in encodings:
charset = "us-ascii"
elif "latin-1" in encodings:
charset = "latin-1"
else:
charset = "utf-8"
href = "/sup_gut/" + filename.split("/")[-1][:-3] + "zip"
if "Title" not in tag_dict:
tag_dict["Title"].append("?")
for i in range(len(tag_dict["Title"])):
for to_remove in self.title_remove:
tag_dict["Title"][i] = tag_dict["Title"][i].replace(to_remove,"")
return href,charset,tag_dict
# this class cleans away Project Gutenberg headers and footers, including copyright and transcriber notes
class TextCleaner:
junk_indicators = ("project gutenberg"," etext"," e-text",
"http:","distributed proofreading",
"distributed\nproofreading", " online"
"html","utf-8","ascii","transcriber's note",
"scanner's note", "\\.net","\\.org","\\.com",
"\\.edu","www\\.", "electronic version",
" email","\\.uk","digitized", "\n\nproduced by",
"david reed", "\ntypographical errors corrected",
"\[note: there is a","etext editor's","u.s. copyright",
"\nerrata"," ebook"," e-book",
"author: ","</pre>", "\[end of","internet archive")
def clean_text(self,text):
text = text.replace("\r\n","\n").replace("\r","\n") # normalize lines
text = re.sub("\n[ *-]+\n","\n\n",text) # get rid of explicit section breaks
#text = re.sub("\[Illustration:?[^\]]*\]","",text)
text = re.sub("<<[^>]+>>","",text)
text = re.sub("[^_]_______________________________________.*_________________________________[^_]","\n\n",text)
lower_text = text.lower()
all_junk_indicies = [0, len(text)]
for junk_indicator in self.junk_indicators:
all_junk_indicies.extend([m.start() for m in re.finditer(junk_indicator,lower_text)])
all_junk_indicies.sort()
best_points = None
best_length = 0
for i in range(len(all_junk_indicies) - 1):
if all_junk_indicies[i+1] - all_junk_indicies[i] > best_length:
best_points = [all_junk_indicies[i],all_junk_indicies[i+1]]
best_length = all_junk_indicies[i+1] - all_junk_indicies[i]
found = False
best_length = float(best_length)
if best_length < 5000: # too small for general method to work reliably
m = re.search("end of [^\\n]*project gutenberg",lower_text)
if m:
best_points[1] = m.start()
i = 0
while all_junk_indicies[i] < best_points[1] - 100:
i += 1
best_points[0] = all_junk_indicies[i-1]
else:
return ""
i = 4
while not found:
looking_for = "\n"*i
result = text.find(looking_for, best_points[0])
if result != -1 and ((best_points[1] - result)/best_length > 0.98 or i == 1):
found = True
i -= 1
return text[result:text.rfind("\n", 0, best_points[1])].strip()
# This guesses at the gender of a person based on their name
class GenderClassifier:
male_pronouns = set(["he","his","him","himself"])
female_pronouns = set(["she","her","herself"])
boundary_tags = set(["said","p","div"])
must_male = set(["mr","sir"])
must_female = set(["mrs","madame","miss","lady"])
prefix_count_cutoff = 5
suffix_count_cutoff = 5
prefix_effect = 0.5
name_shape_add = 10
def add_to_suffix_ratio_dict(self,word,i,add_new=True):
for j in range(len(word)):
suffix = word[j:]
if suffix not in self.suffix_ratio_dict:
if add_new:
self.suffix_ratio_dict[suffix] = [0,0]
else:
continue
self.suffix_ratio_dict[suffix][i] += 1
def remove_from_suffix_ratio_dict(self,word,i):
for j in range(len(word)):
suffix = word[j:]
if suffix in self.suffix_ratio_dict:
self.suffix_ratio_dict[suffix][i] -= 1
if sum(self.suffix_ratio_dict[suffix]) == 0:
del self.suffix_ratio_dict[suffix]
def add_to_prefix_ratio_dict(self,word,i,add_new=True):
for j in range(len(word)):
prefix = word[:-j]
if prefix not in self.prefix_ratio_dict:
if add_new:
self.prefix_ratio_dict[prefix] = [0,0]
else:
continue
self.prefix_ratio_dict[prefix] = [0,0]
self.prefix_ratio_dict[prefix][i] += 1
def remove_from_prefix_ratio_dict(self,word,i):
for j in range(len(word)):
prefix = word[:-j]
if prefix in self.prefix_ratio_dict:
self.prefix_ratio_dict[prefix][i] -= 1
if sum(self.prefix_ratio_dict[prefix]) == 0:
del self.prefix_ratio_dict[prefix]
def __init__(self):
f = open("resources/femaleFirstNames.txt")
self.female_first_names = set()
for line in f:
self.female_first_names.add(line.strip())
f.close()
self.male_first_names = set()
f = open("resources/maleFirstNames.txt")
for line in f:
name = line.strip()
if name not in self.female_first_names:
self.male_first_names.add(name)
else:
print name
f.close()
self.male_female_ratio = float(len(self.male_first_names))/float(len(self.female_first_names))
self.prefix_ratio_dict = {}
self.suffix_ratio_dict = {}
dicts = [self.male_first_names, self.female_first_names]
for i in [0,1]:
for word in dicts[i]:
self.add_to_prefix_ratio_dict(word,i)
self.add_to_suffix_ratio_dict(word,i)
if self.suffix_count_cutoff != -1:
for suffix in self.suffix_ratio_dict.keys():
if sum(self.suffix_ratio_dict[suffix]) < self.suffix_count_cutoff:
del self.suffix_ratio_dict[suffix]
if self.prefix_count_cutoff != -1:
for prefix in self.prefix_ratio_dict.keys():
if sum(self.prefix_ratio_dict[prefix]) < self.prefix_count_cutoff:
del self.prefix_ratio_dict[prefix]
def get_pronoun_ratios(self,text):
pronoun_counts = {}
for i in range(len(text.tags)):
#if text.tags[i].tag == "persName":
# print text.tags[i].tag
# print text.tags[i].attributes
# print text.tokens[text.tags[i].start:text.tags[i].end]
if text.tags[i].tag == "persName" and text.tags[i].attributes and "corresp" in text.tags[i].attributes:
#print "here!!!!!!!!!!!"
char_ID = text.tags[i].attributes["corresp"].strip("#")
if char_ID not in pronoun_counts:
pronoun_counts[char_ID] = [0,0]
earliest_cutoff = len(text.tokens)
j = i - 1
curr_loc = text.tags[i].start
stop = False
while not stop and j >= 0:
if text.tags[j].tag in self.boundary_tags and text.tags[j].end > curr_loc:
earliest_cutoff = text.tags[j].end
stop = True
else:
j -= 1
j = i + 1
stop = False
while not stop and j < len(text.tags):
if text.tags[j].start >= earliest_cutoff:
stop = True
elif text.tags[j].tag in self.boundary_tags or text.tags[j].tag == "persName":
earliest_cutoff = text.tags[j].start
stop = True
else:
j += 1
#print text.tokens[text.tags[i].end:earliest_cutoff]
for j in range(text.tags[i].end, earliest_cutoff):
word = text.tokens[j].lower()
if word in self.male_pronouns:
pronoun_counts[char_ID][0] += 1
break
elif word in self.female_pronouns:
pronoun_counts[char_ID][1] += 1
break
return pronoun_counts
def classify_by_suffix(self,word):
suffix = word
while suffix and suffix not in self.suffix_ratio_dict:
suffix = suffix[1:]
if not suffix:
return ""
else:
if self.suffix_ratio_dict[suffix][1] == 0 or float(self.suffix_ratio_dict[suffix][0])/self.suffix_ratio_dict[suffix][1] > self.male_female_ratio:
return "M"
else:
return "F"
def classify_by_prefix(self,word):
prefix = word
while prefix and prefix not in self.prefix_ratio_dict:
prefix = prefix[:-1]
if not prefix:
return ""
else:
if self.prefix_ratio_dict[prefix][1] == 0 or float(self.prefix_ratio_dict[prefix][0])/self.prefix_ratio_dict[prefix][1] > self.male_female_ratio:
return "M"
else:
return "F"
def classify_by_affix(self,word):
suffix = word
while suffix and suffix not in self.suffix_ratio_dict:
suffix = suffix[1:]
if not suffix:
return ""
prefix = word
while prefix and prefix not in self.prefix_ratio_dict:
prefix = prefix[:-1]
if not prefix:
return ""
combo = [self.prefix_ratio_dict[prefix][0]*self.prefix_effect + self.suffix_ratio_dict[suffix][0], self.prefix_ratio_dict[prefix][1]*self.prefix_effect + self.suffix_ratio_dict[suffix][1]]
if combo[1] == 0 or float(combo[0])/combo[1] > self.male_female_ratio:
return "M"
else:
return "F"
def classify_by_pronoun(self,pronoun_counts,name):
name_tokens = name.split("_")
if name_tokens[0] == "the":
first_word = name_tokens[1]
else:
first_word = name_tokens[0]
first_word = first_word.lower().strip(".")
if first_word in self.must_male:
return "M"
elif first_word in self.must_female:
return "F"
name_result = self.classify(first_word)
if name in pronoun_counts:
if name_result == "M":
pronoun_counts[name][0] += self.name_shape_add
elif name_result == "F":
pronoun_counts[name][1] += self.name_shape_add
if pronoun_counts[name][0] > pronoun_counts[name][1]:
return "M"
else:
return "F"
else:
return name_result
def classify_by_list(self,word):
word = word.lower()
if word in self.female_first_names:
return "F"
elif word in self.male_first_names:
return "M"
else:
return ""
def classify(self,word):
word = word.lower()
if word in self.female_first_names:
return "F"
elif word in self.male_first_names:
return "M"
else:
#return self.classify_by_suffix(word)
return self.classify_by_affix(word)
# this class wraps everything related to genre classification. Not actually
# functional because genres are pre-calculated using separate script
class GenreClassifier:
common_words = set(["whether","poor","dear","do","god","three","thou","thus","nor","says","say","said","any","all","have","had","can","one","is","are","am","be","was","were","which","on","my","how","you","the","a","it","he","she","his","her","i","they","we","at","and","but","when","there","as","who","if","under","over","after","before","this","that","all","what","to","by","in","from","such","here","with","for","of","yes","ah","oh","so","our","no", "not","some","where","now","come","go","dear","then","than","these","those","up","down","out","yours","let","your","there","january","febuary","march","april","may","june","july","august","september","october","november","december","monday","tuesday","wednesday","thursday","friday","saturday","sunday","still","perhaps"])
likely_delimin = set([".","-",":","<","(","_","["])
narrative_words = set(["hissed","declared","repeated","said","asked","replied","answered","cried","responded","added","screamed","wondered","reflected","pondered","ejaculated","rejoined","inquired","says","announced","offered","began","continued","mumbled","whispered","roared", "retorted", "sneered"])
fiction_title = set(["novel","stories","story","adventures","tale","tales","mystery"])
nonfiction_title = set(["discourses", "autobiography","biography","diary","diaries","letters","essay","essays","record","history","speech","speeches","talks","recollections","memoirs","sermons","life"])
poetry_title = set(["poem","poetry", "verse", "ballad", "poetical","ode"])
play_title = set(["play","drama","acts"])
end_words = set(["the end","end","finis","fin"])
'''
def __init__(self,decision_tree_filename):
self.node_dict = {}
f = open(decision_tree_filename)
for line in f:
stuff = line.strip().split(",")
if len(stuff) == 2:
self.node_dict[int(stuff[0])] = [stuff[1]]
else:
self.node_dict[int(stuff[0])] = [int(stuff[1]),int(stuff[2]),stuff[3],float(stuff[4])]
'''
def __init__(self,random_forest_filename):
self.estimators = []
f = open(random_forest_filename)
trees = f.read().split("---------")
for i in range(len(trees) -1):
node_dict = {}
lines = trees[i].split("\n")
for j in range(len(lines) - 1):
stuff = lines[j].strip().split(",")
if len(stuff) == 2:
node_dict[int(stuff[0])] = [stuff[1]]
else:
node_dict[int(stuff[0])] = [int(stuff[1]),int(stuff[2]),stuff[3],float(stuff[4])]
self.estimators.append(node_dict)
def get_feature_dict(self,text,tags):
feature_dict = {}
lines = text
total_lines = 0.0
total_paragraphs = 0.0
expected_no_capital = 0.0
title_words = tags["Title"][0].replace(":"," :").replace(";", " ;").replace(" "," ").lower().split()
feature_dict["title_volume"] = 0
feature_dict["title_twoparts"] = "\t" in tags["Title"][0]
feature_dict["fiction_title"] = 0
feature_dict["nonfiction_title"] = 0
feature_dict["play_title"] = 0
feature_dict["poetry_title"] = 0
feature_dict["title_length"] = len(title_words)
found_key = False
for word in title_words:
if word == "volume" or word == "vol.":
feature_dict["title_volume"] = 1
elif word == ":" or word == ";" or word == u"—":
feature_dict["title_twoparts"] = 1
elif word in self.nonfiction_title and not found_key:
feature_dict["nonfiction_title"] = 1
found_key = True
elif word in self.fiction_title and not found_key:
feature_dict["fiction_title"] = 1
found_key = True
elif word in self.play_title and not found_key:
feature_dict["play_title"] = 1
found_key = True
elif word in self.poetry_title and not found_key:
feature_dict["poetry_title"] = 1
found_key = True
try:
if tags["Author"][0] in tags["Title"][0]:
feature_dict["author_in_title"] = 1
else:
feature_dict["author_in_title"] = 0
except:
feature_dict["author_in_title"] = 0
feature_dict["capital_line_count"] = 0
feature_dict["comma_line_count"] = 0
feature_dict["dash_line_count"] = 0
feature_dict["you_line_count"] = 0
feature_dict["I_line_count"] = 0
feature_dict["she_line_count"] = 0
feature_dict["line_number_count"] = 0
feature_dict["indent_count"] = 0
feature_dict["uncommon_repeat_count"] = 0
feature_dict["two_capital_count"] = 0
feature_dict["act_count"] = 0
feature_dict["chapter_count"] = 0
feature_dict["quote_count"] = 0
feature_dict["early_delim_count"] = 0
feature_dict["headers"] = 0.0
feature_dict["repeated_headers"] = 0
feature_dict["longest_quote_string"] = 0
feature_dict["other_sent_punc"] = 0
feature_dict["end"] = 0
feature_dict["narrative_words"] = 0
feature_dict["illustrations"] = 0
feature_dict["avg_paragraph_len"] = 0
feature_dict["asides_count"] = 0
'''
feature_dict["year"] = 0
feature_dict["month"] = 0
feature_dict["appendix"] = 0
feature_dict["contents"] = 0
feature_dict["cast_list"] = 0
feature_dict["prologue"] = 0
feature_dict["footnotes"] = 0
if line.startswith("[footnote"):
feature_dict["footnote"].add(i)
if line.startswith("["):
feature_dict["start_bracket"].add(i)
if line.endswith("]"):
feature_dict["end_bracket"].add(i)
if text_lines[i].startswith("Illustrated by") or text_lines[i].startswith("Illustrations by"):
feature_dict["illustrated"].add(i)
has_front_indicator = True
if line.startswith("preface") or line.startswith("to the reader") or line.endswith("to the reader") or (line.startswith("history of") and "history of" not in global_tags["Title"][0].lower()):
feature_dict["preface"].add(i)
has_front_header = True
if line.startswith("introduction") or line.startswith("foreword"):
feature_dict["introduction"].add(i)
has_front_header = True
for feature in ["prologue","epilogue","appendix","afterword","glossary","bibliography","index","afterword","postscript"]:
if line == feature or (line.startswith(feature) and i in feature_dict["upper_case"]):
feature_dict[feature].add(i)
'''
start_word_list = set()
repeated_list = {}
repeated_header = set()
indented = False
last_indented = False
quote_string_count = 0
for i in range(len(lines)):
if lines[i].strip():
total_lines += 1
feature_dict["avg_paragraph_len"] += 1
if lines[i][0] == " ":
feature_dict["indent_count"] += 1
last_indented = indented
indented = True
else:
indented = False
if '"' in lines[i]:
feature_dict["quote_count"] += 1
for word in self.narrative_words:
if word in lines[i]:
feature_dict["narrative_words"] += 1
if "!" in lines[i] or "?" in lines[i]:
feature_dict["other_sent_punc"] += 1
#lines[i] = lines[i].strip()
curr_line = lines[i]
while " " in curr_line:
curr_line = curr_line.replace(" "," ")
curr_line = curr_line.strip()
if "I " in curr_line or "I'" in curr_line or " my " in curr_line or "My " in curr_line or " me " in curr_line or " me." in curr_line or " me," in curr_line:
feature_dict["I_line_count"] += 1
if curr_line.startswith("[Illustration"):
feature_dict["illustrations"] += 1
elif ("(" in curr_line and curr_line.find(")", max(curr_line.find("(") - 3,0), min(curr_line.find("(") + 3, len(curr_line))) == -1) or ("[" in curr_line and curr_line.find("]", max(curr_line.find("[") - 3,0), min(curr_line.find("[") + 3,len(curr_line))) == -1):
feature_dict["asides_count"] += 1
words = curr_line.split(" ")
curr_line = curr_line.lower()
if words[-1].endswith(","):
feature_dict["comma_line_count"] += 1
if words[-1].isdigit():
lower_line = lines[i].lower()
if not "act" in lower_line and not "chapter" in lower_line and not "scene" in lower_line:
feature_dict["line_number_count"] += 1
if i > 0 and lines[i-1] and len(words) > 4 and not (lines[i-1].endswith(".") or lines[i-1].endswith("?") or lines[i-1].endswith("!")):
expected_no_capital += 1
if words[0].isalpha() and has_capital(words[0]):
feature_dict["capital_line_count"] += 1
if curr_line in self.end_words:
feature_dict["end"] = 1
if "you" in curr_line:
feature_dict["you_line_count"] += 1
if "She " in curr_line or " she " in curr_line or " her " in curr_line or " her." in curr_line or " her," in curr_line :
feature_dict["she_line_count"] += 1
if "--" in curr_line:
feature_dict["dash_line_count"] += 1
if i > 0 and (not lines[i-1] or (indented and not last_indented)):
total_paragraphs += 1
if (words[0].lower() == "act" or words[0].lower() == "scene") and i != len(lines) -1 and not lines[i+1].strip():
feature_dict["act_count"] += 1
elif words[0].lower() == "chapter" and i != len(lines) -1 and not lines[i+1].strip():
feature_dict["chapter_count"] += 1
elif words[0].lower() in start_word_list:
feature_dict["uncommon_repeat_count"] += 1
repeated_list[words[0].lower()] = repeated_list.get(words[0].lower(),0) + 1
elif (words[0][0].isalpha() or words[0][0] == "_") and len(words[0]) > 2 and words[0].lower() not in self.common_words:
start_word_list.add(words[0].lower())
if len(words) > 2 and not words[0].startswith('"') and has_capital(words[0]) and has_capital(words[1]):
feature_dict["two_capital_count"] += 1
if has_capital(words[0]) and alpha_count(words[0]) > 1 and (not self.likely_delimin.isdisjoint(words[0]) or (len(words) > 1 and not self.likely_delimin.isdisjoint(words[1]))):
feature_dict["early_delim_count"] += 1
if i < len(lines) -1 and not lines[i+1].strip() and len(words) < 5:
feature_dict["headers"] += 1
if lines[i] in repeated_header:
feature_dict["repeated_headers"] += 1
else:
repeated_header.add(lines[i])
if curr_line.startswith('"'):
quote_string_count += 1
if quote_string_count > feature_dict["longest_quote_string"]:
feature_dict["longest_quote_string"] = quote_string_count
else:
quote_string_count = 0
else:
pass
try:
feature_dict["capital_line_count"] /= expected_no_capital
except:
pass
try:
feature_dict["comma_line_count"] /= total_lines
feature_dict["line_number_count"] /= total_lines
feature_dict["indent_count"] /= total_lines
feature_dict["quote_count"] /= total_lines
feature_dict["other_sent_punc"] /= total_lines
feature_dict["narrative_words"] /= total_lines
feature_dict["dash_line_count"] /= total_lines
feature_dict["you_line_count"] /= total_lines
feature_dict["I_line_count"] /= total_lines
feature_dict["she_line_count"] /= total_lines
feature_dict["asides_count"] /= total_lines
except:
pass
try:
feature_dict["repeated_headers"] /= feature_dict["headers"]
except:
pass
try:
feature_dict["uncommon_repeat_count"] /= total_paragraphs
feature_dict["two_capital_count"] /= total_paragraphs
feature_dict["early_delim_count"] /= total_paragraphs
feature_dict["avg_paragraph_len"] = (feature_dict["avg_paragraph_len"] - feature_dict["headers"]) / (total_paragraphs - feature_dict["headers"])
feature_dict["headers"] /= total_paragraphs
except:
pass
return feature_dict
def get_classification(self,feature_dict,node,node_dict):
if len(node) == 1:
return node[0]
else:
if feature_dict[node[2]] <= node[3]:
return self.get_classification(feature_dict,node_dict[node[0]],node_dict)
else:
return self.get_classification(feature_dict,node_dict[node[1]],node_dict)
def classify_genre(self,text,tags):
feature_dict = self.get_feature_dict(text,tags)
classifications = []
for node_dict in self.estimators:
classifications.append(self.get_classification(feature_dict,node_dict[0],node_dict))
results = Counter(classifications)
return max(results.iteritems(),key=operator.itemgetter(1))[0]
# Tokenizer built on top of NLTK tokenizer does a few special things to work
# better with PG texts (for instance, preserves hyphenated words and direction
# of quotes)
class Tokenizer:
base_contractions = ["s", "ll", "d", "re", "m", 've']
base_abbreviations = ["Mr.","Mrs.","Dr.","Ms.","Rev.","St.","etc.","Prof."
"Ltd.","Jr.","Vol.","lbs.","pp.","pg."]
def __init__(self):
self.contractions = set()
for contraction in self.base_contractions:
self.contractions.add(contraction)
self.contractions.add(contraction.upper())
self.abbreviations = set()
for abbreviation in self.base_abbreviations:
self.abbreviations.add(abbreviation)
self.abbreviations.add(abbreviation.upper())
self.left_single_quote = re.compile("([[\s(-]|^)'([^ ])")
self.right_single_quote = re.compile("([^ ])'($|[])\s);,.?!-])")
self.left_double_quote = re.compile('([[\s(-]|^)"([^ ])')
self.right_double_quote = re.compile('([^ ])"($|[])\s;,.?!-])')
self.left_bracket = re.compile('([,-.;?!])([[(])')
self.right_bracket = re.compile('([\])])([,-.?!;])')
f = open('resources/english.pickle')
self.sentence_tokenizer = cPickle.load(f)
f.close()
self.word_tokenizer = regexp.WordPunctTokenizer()
def fix_quotes(self,raw_text):
return self.left_single_quote.sub(u'\\1 ‘ \\2',self.right_single_quote.sub(u'\\1 ’ \\2',self.left_double_quote.sub(u'\\1 “ \\2',self.right_double_quote.sub(u'\\1 ” \\2',raw_text))))
def fix_brackets(self,raw_text):
return self.left_bracket.sub(u'\\1 \\2',self.right_bracket.sub(u'\\1 \\2',raw_text))
def fix_sentence_quotes(self,sentences):
for i in range(1, len(sentences)):
if sentences[i].startswith(u'”') or sentences[i].startswith(u'’'):
sentences[i-1] += " " + sentences[i][:1]
sentences[i] = sentences[i][1:]
def tokenize_span(self,raw_text):
new_text = raw_text.replace("_","")
new_text = self.fix_quotes(new_text)
new_text = self.fix_brackets(new_text)
all_sentences = []
sentences = self.sentence_tokenizer.tokenize(new_text)
self.fix_sentence_quotes(sentences)
new_sentences = []
i = 0
for sentence in sentences:
sentence = self.word_tokenizer.tokenize(sentence.strip().replace("--",u"—").replace("-", "hYpppHeN"))
i = 0
if not sentence:
continue
if "hYpppHeN" in sentence[0]:
sentence[0] = sentence[0].replace("hYpppHeN", "-")
while i < len(sentence) -2:
if sentence[i+1] == "'":
if sentence[i+2] in self.contractions:
sentence[i + 1] += sentence[i+2]
del sentence[i+2]
elif sentence[i+2] == 't' and sentence[i].endswith('n'):
if not sentence[i] == "can":
sentence[i] = sentence[i][:-1]
sentence[i+1] = "n't"
del sentence[i+2]
else:
sentence[i] += sentence[i+1] + sentence[i+2]