forked from Cardal/Kaggle_AllenAIscience
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai2_Cardal.py
5408 lines (4962 loc) · 315 KB
/
ai2_Cardal.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
'''
Kaggle "The Allen AI Science Challenge" competition
Oct 2015 - Feb 2016
Kaggle username: "Cardal"
'''
from sklearn import preprocessing, grid_search, cross_validation, ensemble, metrics, linear_model, neighbors, svm, kernel_ridge, cross_decomposition
from sklearn.metrics import roc_curve, auc
from sklearn.feature_extraction import DictVectorizer
import nltk
from nltk.stem.porter import PorterStemmer
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem.snowball import EnglishStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import wordnet as wn
import cPickle
import pandas as pd
import numpy as np
import urllib2
import scipy
import scipy.optimize
import time
import sys
import csv
import re
import gc
import os
# This condition is here since I don't have PyLucene on my Windows system
if (len(sys.argv) >= 3) and (sys.argv[1] == 'prep') and (int(sys.argv[2]) >= 21):
import lucene
from java.io import File, StringReader
from org.apache.lucene.analysis.core import WhitespaceAnalyzer
from org.apache.lucene.analysis.miscellaneous import LimitTokenCountAnalyzer
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.document import Document, Field, StoredField, StringField, TextField
from org.apache.lucene.search.similarities import BM25Similarity
from org.apache.lucene.index import IndexWriter, IndexWriterConfig, DirectoryReader, MultiFields, Term
from org.apache.lucene.queryparser.classic import MultiFieldQueryParser, QueryParser
from org.apache.lucene.search import BooleanClause, IndexSearcher, TermQuery
from org.apache.lucene.store import MMapDirectory, SimpleFSDirectory
from org.apache.lucene.util import BytesRefIterator, Version
#################################################################################################
# I/O functions
#################################################################################################
def read_input_file(base_dir, filename, max_rows=999999999, use_cols=None, index_col=0, sep=','):
'''
Read an input file
'''
# print '=> Reading input file %s' % filename
dataf = pd.read_table('%s/%s' % (base_dir, filename), index_col=index_col, nrows=max_rows, sep=sep)
if 'correctAnswer' in dataf.columns:
dataf = dataf[[(ca in ['A','B','C','D']) for ca in dataf['correctAnswer']]]
dataf['ID'] = dataf.index
return dataf
def save_to_pkl(filename, data):
with open(filename, "wb") as f:
cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL)
def load_from_pkl(filename):
if not os.path.exists(filename):
return None
with open(filename, "rb") as f:
data = cPickle.load(f)
return data
def create_dirs(dirs):
'''
Make sure the given directories exist. If not, create them
'''
for dir in dirs:
if not os.path.exists(dir):
print 'Creating directory %s' % dir
os.mkdir(dir)
def save_submission(submission_filename, preds):
out_df = pd.DataFrame({'id': preds.keys(), 'correctAnswer': preds.values()})
out_df = out_df.set_index('id')
out_df.to_csv(submission_filename)
print 'Saved submission file: %s' % submission_filename
#################################################################################################
# Stat utilities
#################################################################################################
def normalize_scores(scores, num_scores_per_row, pow=1, laplace=1E-100):
'''
Normalize the scores of each row. Use pow=0 for ranks.
'''
assert (num_scores_per_row > 0) and (laplace > 0)
num_rows = len(scores) / num_scores_per_row
assert num_rows*num_scores_per_row == len(scores)
scores_mat = np.array(scores).reshape((num_rows, num_scores_per_row))
if pow == 0:
# Compute ranks
ranks = np.ones((num_rows, num_scores_per_row)) * (-1)
for r in range(num_rows):
ranks[r] = scipy.stats.rankdata(scores_mat[r], 'average') / num_scores_per_row
assert np.all(ranks != -1)
normed = ranks
else:
# Normalize using given power
scores_mat += laplace # to handle cases where all scores are 0, and also as a Laplace correction
assert np.all(scores_mat > 0)
normed = (scores_mat ** pow) / np.array([np.sum(scores_mat ** pow, axis=1)]).transpose()
return normed.flatten()
#################################################################################################
# Parsers
#################################################################################################
class WordParser(object):
'''
WordParser - base class for parsers
'''
def __init__(self, min_word_length=2, max_word_length=25, ascii_conversion=True):
self.min_word_length = min_word_length
self.max_word_length = max_word_length
self.ascii_conversion = ascii_conversion
def filter_words_by_length(self, words):
return [word for word in words if len(word)>=self.min_word_length and len(word)<=self.max_word_length]
def convert_ascii(self, text):
if self.ascii_conversion:
return AsciiConvertor.convert(text)
return text
def parse(self, text, calc_weights=False):
if calc_weights:
return text, {}
else:
return text
class NltkTokenParser(WordParser):
'''
NLTK parser, supports tags (noun, verb, etc.)
'''
# See nltk.help.upenn_tagset('.*')
TAG_TO_POS = {'NN': wn.NOUN, 'NNP': wn.NOUN, 'NNPS': wn.NOUN, 'NNS': wn.NOUN,
'VB': wn.VERB, 'VBD': wn.VERB, 'VBG' : wn.VERB, 'VBN': wn.VERB, 'VBP': wn.VERB, 'VBZ': wn.VERB,
'RB': wn.ADV, 'RBR': wn.ADV , 'RBS' : wn.ADV , 'RP' : wn.ADV,
'JJ': wn.ADJ , 'JJR': wn.ADJ , 'JJS' : wn.ADJ }
def __init__(self, min_word_length=2, word_func=None, tolower=True, ascii_conversion=True, tuples=[1], ignore_special_words=True,
tag_weight_func=lambda tag: 1.0, word_func_requires_tag=True):
self.word_func = word_func
self.tolower = tolower
self.tuples = tuples
self.ignore_special_words = ignore_special_words
self.tag_weight_func = tag_weight_func
self.word_func_requires_tag = word_func_requires_tag
assert set([1]).issuperset(self.tuples)
WordParser.__init__(self, min_word_length=min_word_length, ascii_conversion=ascii_conversion)
def parse(self, text, calc_weights=False):
text = self.convert_ascii(text)
tokens = nltk.word_tokenize(text)
if calc_weights or self.word_func_requires_tag:
tagged_tokens = nltk.pos_tag(tokens)
else: # save time - don't use tags
tagged_tokens = zip(tokens,[None]*len(tokens))
##tagged_tokens = nltk.pos_tag(tokens)
words, weights, self.tags = [], [], []
for word,tag in tagged_tokens:
if len(word)>=self.min_word_length and len(word)<=self.max_word_length:
words.append(word.lower() if self.tolower else word)
weights.append(self.tag_weight_func(tag) if calc_weights else 0)
self.tags.append(tag)
self.word_weights = {}
# Filter special words
if self.ignore_special_words:
filtered = np.array([SpecialWords.filter1(word) for word in words])
if np.all(filtered == False): # we're about to filter all the words -> instead, don't filter anything
filtered = [True]*len(words)
else:
filtered = [True]*len(words) # no filtering
if self.word_func is not None:
fwords = []
for word,wgt,fltr,tag in zip(words, weights, filtered, self.tags):
if fltr:
try:
fword = str(self.word_func(word, NltkTokenParser.TAG_TO_POS.get(tag,None)))
except UnicodeDecodeError:
fword = word
# fword = self._apply_word_func(word, tag)
if type(fword)==list:
fwords += fword
if calc_weights:
for fw in fword:
self.word_weights[fw] = np.max([self.word_weights.get(fw,-1.0), wgt])
else:
fwords.append(fword)
if calc_weights:
self.word_weights[fword] = np.max([self.word_weights.get(fword,-1.0), wgt])
words = fwords
else:
fwords = []
for word,wgt,fltr in zip(words, weights, filtered):
if fltr:
fwords.append(word)
if calc_weights:
self.word_weights[word] = np.max([self.word_weights.get(word,-1.0), wgt])
words = fwords
ret_words = []
if 1 in self.tuples:
ret_words += words
if calc_weights:
return ret_words, self.word_weights
else:
return ret_words
class SimpleWordParser(WordParser):
'''
SimpleWordParser - supports tuples
'''
def __init__(self, stop_regexp='[\-\+\*_\.\:\,\;\?\!\'\"\`\\\/\)\]\}]+ | [\*\:\;\'\"\`\(\[\{]+|[ \t\r\n\?]',
min_word_length=2, word_func=None, tolower=True, ascii_conversion=True, ignore_special_words=True,
split_words_regexp=None, # for additional splitting of words, provided that all parts are longer than min_word_length, eg, split_words_regexp='[\-\+\*\/\,\;\:\(\)]'
tuples=[1]):
self.stop_regexp = re.compile(stop_regexp)
self.word_func = word_func
self.tolower = tolower
self.ignore_special_words = ignore_special_words
self.split_words_regexp = None if split_words_regexp is None else re.compile(split_words_regexp)
self.tuples = tuples
assert set([1,2,3,4]).issuperset(self.tuples)
WordParser.__init__(self, min_word_length=min_word_length, ascii_conversion=ascii_conversion)
def parse(self, text, calc_weights=False):
if self.tolower:
text = text.lower()
text = ' ' + text.strip() + ' ' # add ' ' at the beginning and at the end so that, eg, a '.' at the end of the text will be removed, and "'''" at the beginning will be removed
text = self.convert_ascii(text)
words = re.split(self.stop_regexp, text)
if self.split_words_regexp is not None:
swords = []
for word in words:
w_words = re.split(self.split_words_regexp, word)
if len(w_words) == 1:
swords.append(w_words[0])
else:
if np.all([len(w)>=self.min_word_length for w in w_words]):
swords += w_words
else:
swords.append(word) # don't split - some parts are too short
words = swords
if self.ignore_special_words:
words = SpecialWords.filter(words)
if self.word_func is not None:
fwords = []
for word in words:
try:
fword = str(self.word_func(word))
except UnicodeDecodeError:
fword = word
fwords.append(fword)
words = fwords
words = self.filter_words_by_length(words)
ret_words = []
if 1 in self.tuples:
ret_words += words
if 2 in self.tuples:
ret_words += ['%s %s'%(words[i],words[i+1]) for i in range(len(words)-1)]
if 3 in self.tuples:
ret_words += ['%s %s %s'%(words[i],words[i+1],words[i+2]) for i in range(len(words)-2)]
if 2 in self.tuples:
ret_words += ['%s %s'%(words[i],words[i+2]) for i in range(len(words)-2)]
if 4 in self.tuples:
ret_words += ['%s %s %s %s'%(words[i],words[i+1],words[i+2],words[i+3]) for i in range(len(words)-3)]
if 3 in self.tuples:
ret_words += ['%s %s %s'%(words[i],words[i+2],words[i+3]) for i in range(len(words)-3)]
ret_words += ['%s %s %s'%(words[i],words[i+1],words[i+3]) for i in range(len(words)-3)]
if 2 in self.tuples:
ret_words += ['%s %s'%(words[i],words[i+3]) for i in range(len(words)-3)]
if 3 not in self.tuples:
ret_words += ['%s %s'%(words[i],words[i+2]) for i in range(len(words)-2)]
if calc_weights:
return ret_words, {}
else:
return ret_words
#################################################################################################
# Corpus preparation
#################################################################################################
class CorpusReader(object):
'''
CorpusReader - base class for corpus readers
'''
PAGE_NAME_PREFIX = '<PAGE>'
SECTION_NAME_PREFIX = '<SECTION>'
PART_NAMES_IGNORE = set(['introduction', 'summary'])
def __init__(self, min_chars_per_line=50, min_words_per_section=50, debug_flag=False):
self.min_chars_per_line = min_chars_per_line
self.min_words_per_section = min_words_per_section
self.debug_flag = debug_flag
self._reset(outfile=None, stop_words=None, pos_words=None, page_name_word_sets=None, corpus_words=None,
min_pos_words_in_page_name=-1, min_pos_words_in_section=-1,
use_all_pages_match_pos_word=False, use_all_pages_match_sets=False, always_use_first_section=False,
action=None)
self.sections_to_use = None
def _reset(self, outfile, stop_words, pos_words, page_name_word_sets, corpus_words,
min_pos_words_in_page_name, min_pos_words_in_section, use_all_pages_match_pos_word, use_all_pages_match_sets, always_use_first_section,
action):
if (stop_words is not None) and (pos_words is not None) and (len(stop_words.intersection(pos_words)) > 0):
print 'Stop words contain pos words - removing from pos words: %s' % stop_words.intersection(pos_words)
pos_words = pos_words.difference(stop_words)
assert (stop_words is None) or len(stop_words.intersection(pos_words))==0
self.outfile = outfile
self.stop_words, self.pos_words, self.page_name_word_sets, self.corpus_words = stop_words, pos_words, page_name_word_sets, corpus_words
self.min_pos_words_in_page_name, self.min_pos_words_in_section = min_pos_words_in_page_name, min_pos_words_in_section
self.use_all_pages_match_pos_word, self.use_all_pages_match_sets = use_all_pages_match_pos_word, use_all_pages_match_sets
self.always_use_first_section = always_use_first_section
self.action = action
self._outf, self._locdic = None, None
self.num_pages, self.num_sections = 0, 0
self.num_section_action = 0
self.pages_in_corpus = set() # names of pages that are actually in the corpus
def set_sections_to_use(self, sections_to_use):
if sections_to_use is None:
self.sections_to_use = sections_to_use
else:
self.sections_to_use = set(sections_to_use)
def _start_action(self):
self.pages_in_corpus = set()
if self.action == 'write':
self._outf = open(self.outfile,'w')
elif self.action == 'locdic':
self._locdic = LocationDictionary(save_locations=False, doc_name_weight=0)
else:
raise ValueError('Unsupported action (%s)' % self.action)
def _end_action(self):
if self._outf is not None:
self._outf.close()
self._outf = None
# Write pages_in_corpus
if self.action == 'write':
save_to_pkl('%s.pages.pkl' % self.outfile, self.pages_in_corpus)
gc.collect()
@staticmethod
def part_name_from_words(words, number):
if (len(words) == 1) and (words[0] in CorpusReader.PART_NAMES_IGNORE):
words = []
return '%s __%d' % (' '.join(words), number)
@staticmethod
def words_from_part_name(part_name):
words = part_name.split(' ')
assert words[-1].startswith('__')
return words[:-1]
def _add_page(self, page_name, page_name_words):
# print 'Adding page "%s"' % page_name
self.num_pages += 1
# if page_name != 'Hayashi track': return
if self.action == 'write':
# print 'writing page %s' % page_name
self._outf.write('%s%s\n' % (CorpusReader.PAGE_NAME_PREFIX, CorpusReader.part_name_from_words(page_name_words, self.num_pages)))
def _check_page_name(self, page_name, page_name_words):
'''
Returns True if page should be used; False if it should be skipped
'''
if self.use_all_pages_match_sets and (tuple(sorted(page_name_words)) in self.page_name_word_sets):
# if self.debug_flag:
# print 'Page "%s" matches page_name_word_sets -> using page' % page_name
return True
num_pos_words_in_page_name = len(set(page_name_words).intersection(self.pos_words))
if self.use_all_pages_match_pos_word and (num_pos_words_in_page_name > 0):
# if self.debug_flag:
# print 'Page "%s" matches pos word(s) (%s) -> using page' % (page_name, set(page_name_words).intersection(self.pos_words))
return True
if num_pos_words_in_page_name >= self.min_pos_words_in_page_name:
# if self.debug_flag:
# print 'Page "%s" has enough pos words (%s -> %d) -> using page' % (page_name, ','.join(page_name_words), num_pos_words_in_page_name)
return True
return False
def _add_section(self, page_name, page_name_words, section_name, section_name_words, section_number, section_words):
'''
Returns 1 if the section was added, 0 otherwise
'''
self.num_sections += 1
# if page_name != 'Hayashi track': return
if ((not self.always_use_first_section) or (section_number > 1)) and (len(section_words) < self.min_words_per_section):
if self.debug_flag:
print 'section "%s" (%d) too short (%d words)' % (section_name, section_number, len(section_words))
return 0
if not self._check_page_name(page_name, page_name_words):
return 0
if (self.sections_to_use is not None) and (section_name not in self.sections_to_use):
if self.debug_flag:
print 'section "%s" (%d) not in sections_to_use set' % (section_name, section_number)
return 0
if self.stop_words is not None:
section_words = [w for w in section_words if not w in self.stop_words]
num_pos_words_in_section = len(set(section_words).intersection(self.pos_words))
if ((not self.always_use_first_section) or (section_number > 1)) and (num_pos_words_in_section < self.min_pos_words_in_section):
if self.debug_flag:
print 'section "%s" (%d) has too few pos words (%d)' % (section_name, section_number, num_pos_words_in_section)
return 0
if self.debug_flag:
print 'page "%s" section "%s" (%d) has %d pos words (total %d words)' % (page_name, section_name, section_number, num_pos_words_in_section, len(section_words))
if self.corpus_words is not None:
section_words = [w for w in section_words if w in self.corpus_words]
if self.action == 'write':
self._outf.write('%s%s\n' % (CorpusReader.SECTION_NAME_PREFIX, CorpusReader.part_name_from_words(section_name_words, section_number)))
# self._outf.write('%d pos words: %s\n' % (num_pos_words_in_section, set(section_words).intersection(self.pos_words))) # DEBUG...
self._outf.write('%s\n' % ' '.join(section_words))
self.num_section_action += 1
elif self.action == 'locdic':
self._locdic.add_words('%s/%s' % (CorpusReader.part_name_from_words(page_name_words, self.num_pages),
CorpusReader.part_name_from_words(section_name_words, section_number)),
page_name_words + section_name_words, section_words)
self.num_section_action += 1
self.pages_in_corpus.add(page_name)
return 1
@staticmethod
def build_locdic_from_outfile(filename, parser=SimpleWordParser(),
min_word_docs_frac=0, max_word_docs_frac=0.2, min_word_count_frac=0, max_word_count_frac=0.01,
doc_name_weight=0):
locdic = LocationDictionary(save_locations=False, doc_name_weight=doc_name_weight)
locdic.set_search_word_filter(min_word_docs_frac=min_word_docs_frac, max_word_docs_frac=max_word_docs_frac,
min_word_count_frac=min_word_count_frac, max_word_count_frac=max_word_count_frac)
num_pages, num_sections = 0, 0
page_name, section_name = None, None
num_lines = 0
if type(filename)==str:
assert file is not None
filenames = [filename]
else:
assert not np.any([(fn is None) for fn in filename])
filenames = filename # list of file names
for ifname,fname in enumerate(filenames):
print 'Building locdic from file #%d: %s' % (ifname, fname)
with open(fname,'rt') as infile:
for text in infile:
# print '%s' % text
if len(text)==0:
print 'Reached EOF'
break # EOF
if text.startswith(CorpusReader.PAGE_NAME_PREFIX):
page_name = text[len(CorpusReader.PAGE_NAME_PREFIX):].strip()
section_name = None
num_pages += 1
elif text.startswith(CorpusReader.SECTION_NAME_PREFIX):
section_name = text[len(CorpusReader.SECTION_NAME_PREFIX):].strip()
num_sections += 1
else:
assert (page_name is not None) and (section_name is not None)
#section_words = text.split(' ')
section_words = parser.parse(text, calc_weights=False) #True)
if False:
print 'Adding words: %s (weights: %s)' % (section_words, weights)
locdic.add_words('F%d/%s/%s' % (ifname, page_name, section_name), CorpusReader.words_from_part_name(page_name) + CorpusReader.words_from_part_name(section_name),
section_words)
num_lines += 1
if num_lines % 100000 == 0:
print ' read %d lines: %d pages, %d sections -> %d words' % (num_lines, num_pages, num_sections, len(locdic.word_ids))
# skjdkjjkkj()
return locdic
class WikiReader(CorpusReader):
'''
WikiReader - read a Wiki corpus
'''
# List of words that appear in >10% of (a sample of) Wiki docs, after manual removal of some words
# List does not include the NLTK stop words
WIKI_STOP_WORDS = set(['also', 'one', 'known', 'new', 'two', 'may', 'part', 'used', 'many', 'made', 'since',
'including', 'later', 'well', 'became', 'called', 'three', 'named', 'second', 'several', 'early',
'often', 'however', 'best', 'use', 'although', 'within'])
# Regexp for page names to ignore
IGNORE_PAGES = re.compile('(\S[\:]\S)|([\(]disambiguation[\)])|(Wikipedia)')
NEW_PAGE_SUBSTR , NEW_PAGE_RE = '<title>' , re.compile('<title>(.*)</title>')
CATEGORY_SUBSTR , CATEGORY_RE = '[[Category:', re.compile('[\[]+Category[\:]([^\]\|]*)([\|][^\]\|]*)*[\]]+') # eg, "[[Category:Social theories]]"
CATEGORY_SUBSTR2 , CATEGORY_RE2 = '{{' , re.compile('[\{][\{]([^\}]+)[\}][\}]\s*<[\/]text>') # eg, "{{music-stub}}</text>" (in SimpleWiki)
PAGE_REDIRECT_SUBSTR, PAGE_REDIRECT_RE = '<redirect' , re.compile('\s*<redirect') # eg, " <redirect title="Light pollution" />" (in SimpleWiki)
NEW_SECTION_SUBSTR , NEW_SECTION_RE = '==' , re.compile('\s*=[=]+([^=]*)=[=]+\s*')
CATEGORY_PAGE_NAME = re.compile('Category[\:](.*)')
# Text replacements
RE_REMOVALS0 = [(sr,re.compile(rr)) for sr,rr in [('[', '[\[]+[^\]\:]+[\:][^\]]+[\]]+'),
('{{', '[\{][\{][^\}]+[\}][\}]')]]
BLANKS_CONVERSIONS = ['"', '&nbsp;', '&', ' ', '|']
OTHER_CONVERSIONS = [('<', '<'), ('>', '>'),
(chr(195)+chr(164), 'a'), (chr(195)+chr(167), 'c'), (chr(195)+chr(169), 'e'), (chr(195)+chr(184), 'o'), (chr(197)+chr(143), 'o'),
(chr(194)+chr(188), '1/4'),
(chr(194)+chr(183), '*'),
(chr(226)+chr(128)+chr(152), "'" ), (chr(226)+chr(128)+chr(153), "'" ),
(chr(226)+chr(128)+chr(156), '"' ), (chr(226)+chr(128)+chr(157), '"' ),
(chr(226)+chr(128)+chr(147), ' - '), (chr(226)+chr(128)+chr(148), ' - '), (chr(226)+chr(136)+chr(146), '-')]
RE_REMOVALS = [(sr,re.compile(rr)) for sr,rr in [#('{{', '[\{][\{][^\}]+[\}][\}]'),
#('<!--', '<![\-][\-][^\&]*(<[^\&]*>[^\&]*)*[\-][\-]>'),
#('<', '<[^\&]*>'),
('<ref', '<ref[^\>]*>[^\<\>]+<[\/]ref>'),
#('[http:', '[\[]http:[^\]]+[\]]'),
('<', '<[^\>]*>'),
("''", "[']+"),
('wikt:', 'wikt:\S+')]]
STR_REMOVALS = ['[[',']]', '#*:','#*']
def __init__(self, wiki_type, debug_flag=False):
assert wiki_type in ['wiki', 'simplewiki', 'wiktionary', 'wikibooks', 'wikiversity']
self.wiki_type = wiki_type
if self.wiki_type == 'wiki':
min_chars_per_line, min_words_per_section = 50, 50
elif self.wiki_type == 'simplewiki':
min_chars_per_line, min_words_per_section = 1, 1
elif self.wiki_type == 'wiktionary':
min_chars_per_line, min_words_per_section = 1, 3
elif self.wiki_type == 'wikibooks':
min_chars_per_line, min_words_per_section = 1, 10
elif self.wiki_type == 'wikiversity':
min_chars_per_line, min_words_per_section = 1, 3
CorpusReader.__init__(self, min_chars_per_line=min_chars_per_line, min_words_per_section=min_words_per_section, debug_flag=debug_flag)
if self.wiki_type == 'wiktionary':
self.set_sections_to_use(['Noun'])
def search_categories(self, category, target_categories, max_depth=5):
checked_categories = set()
categories_to_check = set([(category, 0)])
while len(categories_to_check) > 0:
cat, depth = categories_to_check.pop()
# print 'Checking %s' % cat
if cat in target_categories:
return depth
checked_categories.add(cat)
if self.parent_categories.has_key(cat) and depth+1 <= max_depth:
# if len(self.parent_categories[cat].difference(checked_categories).intersection(['Medicine','Medical specialties','Psychiatry','Neurophysiology','Mind'])) > 0:
# print '%s -> adding %s' % (cat, sorted(self.parent_categories[cat].difference(checked_categories)))
categories_to_check.update([(c,depth+1) for c in self.parent_categories[cat].difference(checked_categories)])
return -1
def read_sub_categories(self, wikifile, max_read_lines=None):
print '=> Reading sub categories'
self.all_categories, self.parent_categories = set(), {}
category = None
num_lines = 0
with open(wikifile,'rt') as infile:
for text in infile:
if len(text)==0:
print 'Reached EOF'
break # EOF
num_lines += 1
if (max_read_lines is not None) and (num_lines > max_read_lines):
break
if num_lines % 1000000 == 0:
print 'Read %d lines, total of %d categories...' % (num_lines, len(self.all_categories))
gc.collect()
if WikiReader.NEW_PAGE_SUBSTR in text:
new_page = re.findall(WikiReader.NEW_PAGE_RE, text)
if len(new_page)>0:
assert len(new_page)==1
page_name = new_page[0]
# print 'page "%s"' % page_name
cmatch = re.match(WikiReader.CATEGORY_PAGE_NAME, page_name)
if cmatch is not None:
category = cmatch.groups(0)[0].strip()
self.all_categories.add(category)
# if category == 'mac os software':
# print '%s' % text
assert (not self.parent_categories.has_key(category)) #or (len(self.parent_categories[category])==0)
self.parent_categories[category] = set()
# print 'Category "%s"' % category
else:
# print ' no match'
category = None
continue
if category is not None:
p_category = None
if WikiReader.CATEGORY_SUBSTR in text:
p_category = re.match(WikiReader.CATEGORY_RE, text)
elif WikiReader.CATEGORY_SUBSTR2 in text:
p_category = re.match(WikiReader.CATEGORY_RE2, text)
if p_category is not None:
assert len(p_category.groups())>=1
parent_name = p_category.groups(0)[0].strip()
self.all_categories.add(parent_name)
self.parent_categories[category].add(parent_name)
print 'Read %d lines, %d categories' % (num_lines, len(self.all_categories))
def read_pages_in_categories(self, wikifile, use_categories=None, max_read_lines=None):
print '=> Reading pages in %s categories' % ('ALL' if use_categories is None else len(use_categories))
pages_in_categories = set()
page_name, page_categories = None, set()
num_lines = 0
with open(wikifile,'rt') as infile:
for text in infile:
if len(text)==0:
print 'Reached EOF'
break # EOF
num_lines += 1
if (max_read_lines is not None) and (num_lines > max_read_lines):
break
if num_lines % 1000000 == 0:
print 'Read %d lines, %d pages so far...' % (num_lines, len(pages_in_categories))
gc.collect()
if WikiReader.NEW_PAGE_SUBSTR in text:
new_page = re.findall(WikiReader.NEW_PAGE_RE, text)
if len(new_page)>0:
assert len(new_page)==1
# Check previous page
if len(page_categories) > 0:
assert page_name is not None
pages_in_categories.add(page_name)
page_name = new_page[0]
page_categories = set()
continue
category = None
if WikiReader.CATEGORY_SUBSTR in text:
category = re.match(WikiReader.CATEGORY_RE, text)
elif WikiReader.CATEGORY_SUBSTR2 in text:
category = re.match(WikiReader.CATEGORY_RE2, text)
if category is not None:
assert len(category.groups())>=1
assert page_name is not None
cat_name = category.groups(0)[0].strip()
if (re.search(WikiReader.IGNORE_PAGES, page_name) is None) and ((use_categories is None) or (cat_name in use_categories)):
# print 'Found category %s for page %s' % (cat_name, page_name)
page_categories.add(cat_name)
#self.all_categories.add(cat_name)
# Check last page
if len(page_categories) > 0:
assert page_name is not None
pages_in_categories.add(page_name)
print 'Read %d lines, %d pages in %d categories' % (num_lines, len(pages_in_categories), len(use_categories))
return pages_in_categories
@staticmethod
def text_replcaments(text):
for sr,rr in WikiReader.RE_REMOVALS0:
if sr in text:
text = re.sub(rr, ' ', text)
for bc in WikiReader.BLANKS_CONVERSIONS:
text = text.replace(bc, ' ')
# print '----------->'
# print '%s' % text
for oc,cc in WikiReader.OTHER_CONVERSIONS:
text = text.replace(oc, cc)
# DEAL WITH HIGH ASCIIs...
if True:
text = ''.join([(c if ord(c)<128 else ' ') for c in text])
else:
if len([c for c in text if ord(c)>=128])>0:
print '%s' % ''.join([(c if ord(c)<128 else ' chr(%d) '%ord(c)) for c in text])
assert False, 'chr > 127'
# print '++++++'
# print 'before re_removals: %s' % text
# print '++++++'
for sr,rr in WikiReader.RE_REMOVALS:
if sr in text:
text = re.sub(rr, ' ', text)
for sr in WikiReader.STR_REMOVALS:
text = text.replace(sr, '')
return text
def read(self, wikifile, outfile, use_pages=None, max_read_lines=None,
only_first_section_per_page=False, max_sections_per_page=99999999,
parser = SimpleWordParser(tolower=True, ascii_conversion=True, ignore_special_words=False),
stop_words=set(), pos_words=set(),
page_name_word_sets=None, corpus_words=None,
min_pos_words_in_page_name=1, min_pos_words_in_section=5,
use_all_pages_match_pos_word=False, use_all_pages_match_sets=False, always_use_first_section=False,
action='write'):
print '=> Reading Wiki corpus (%s)' % self.wiki_type
if use_pages is not None:
print 'Using set of %d pages' % len(use_pages)
self._reset(outfile=outfile, stop_words=stop_words, pos_words=pos_words, page_name_word_sets=page_name_word_sets, corpus_words=corpus_words,
min_pos_words_in_page_name=min_pos_words_in_page_name, min_pos_words_in_section=min_pos_words_in_section,
use_all_pages_match_pos_word=use_all_pages_match_pos_word, use_all_pages_match_sets=use_all_pages_match_sets,
always_use_first_section=always_use_first_section,
action=action)
skip_lines_first_1char = set(['\n']) #,'=','{','}','|','!',';','#']) #,' ','*'])
skip_lines_first_6chars = set(['<media', '[[File', '[[Imag', '[[Cate'])
content_lines_re = re.compile('^([^<])|([<]text)')
if self.wiki_type == 'wiki':
skip_lines_first_1char.update(['=','{','}','|','!',';','#',' ','*'])
self._start_action()
page_name, section_name, section_name_words, section_in_page = None, None, [], 0
page_name_words, section_words, section_text = [], [], ''
num_sections_added_in_page = 0
skip_page = True
start_time = time.time()
num_lines = 0
with open(wikifile,'rt') as infile:
for text in infile:
# if not skip_page:
# print '%s' % text
# if len(re.findall(WikiReader.NEW_PAGE_RE, text)) > 0:
# print '======== %s' % text
# if re.match('\s*[\{][\{]([^\}]+)[\}][\}]\s*<[\/]text>', text) is not None:
# print text
# continue
if len(text)==0:
print 'Reached EOF'
break # EOF
num_lines += 1
if (max_read_lines is not None) and (num_lines > max_read_lines):
break
if num_lines % 1000000 == 0:
print 'Read %d lines, %d pages, %d sections so far, %d sections actioned...' % (num_lines, self.num_pages, self.num_sections, self.num_section_action)
gc.collect()
if WikiReader.NEW_PAGE_SUBSTR in text:
new_page = re.findall(WikiReader.NEW_PAGE_RE, text)
if len(new_page)>0:
assert len(new_page)==1
# Add last section from previous page
if (not skip_page) and ((not only_first_section_per_page) or (section_in_page == 1)) and (num_sections_added_in_page < max_sections_per_page):
# print '---------------------------------'
# print 'FULL: %s' % section_text
section_text = WikiReader.text_replcaments(section_text)
# print '---------------------------------'
# print 'GOT: %s' % section_text
# print '---------------------------------'
# print ''
section_words = parser.parse(section_text)
num_sections_added_in_page += self._add_section(page_name, page_name_words, section_name, section_name_words, section_in_page, section_words)
page_name = new_page[0]
page_name_words = parser.parse(page_name)
# print '------> new page: %s (%d)' % (page_name, self.num_pages)
section_in_page, section_name, section_name_words, section_words, section_text = 1, '', [], [], ''
num_sections_added_in_page = 0
skip_page = (re.search(WikiReader.IGNORE_PAGES, page_name) is not None) or ((use_pages is not None) and (page_name not in use_pages))
skip_page = skip_page or (not self._check_page_name(page_name, page_name_words))
# if ('light' not in page_name_words) or ('year' not in page_name_words):
# skip_page = True
# else:
# skip_page = False
# print 'not skipping page "%s": %s' % (page_name, page_name_words)
# if 'Wikipedia' in page_name:
# print 'page %s -> skip = %s' % (page_name, skip_page)
if not skip_page:
self._add_page(page_name, page_name_words)
continue
# if page_name != 'Hayashi track': continue
if skip_page: continue
if (section_in_page == 1) and (len(section_words) == 0) and (WikiReader.PAGE_REDIRECT_SUBSTR in text):
if re.match(WikiReader.PAGE_REDIRECT_RE, text):
# print 'Redirect -> skipping page "%s"' % page_name
skip_page = True
if skip_page: continue
if WikiReader.NEW_SECTION_SUBSTR in text:
new_section = re.match(WikiReader.NEW_SECTION_RE, text)
if new_section is not None:
assert len(new_section.groups())==1
# Add previous section
if ((not only_first_section_per_page) or (section_in_page == 1)) and (num_sections_added_in_page < max_sections_per_page):
# print '---------------------------------'
# print 'FULL: %s' % section_text
section_text = WikiReader.text_replcaments(section_text)
# print '---------------------------------'
# print 'GOT: %s' % section_text
# print '---------------------------------'
# print ''
section_words = parser.parse(section_text)
num_sections_added_in_page += self._add_section(page_name, page_name_words, section_name, section_name_words, section_in_page, section_words)
section_in_page += 1
section_name, section_words, section_text = new_section.groups(0)[0], [], ''
section_name = WikiReader.text_replcaments(section_name)
section_name_words = parser.parse(section_name)
# print '---> new section: %s (%d)' % (section_name, section_in_page)
continue
if text[ 0] in skip_lines_first_1char: continue
if text[:6] in skip_lines_first_6chars: continue
if len(text) < self.min_chars_per_line: continue
text = text.strip()
if re.match(content_lines_re, text) is None: continue
section_text += ' ' + text.strip() + ' '
# Add last section
if (not skip_page) and ((not only_first_section_per_page) or (section_in_page == 1)) and (num_sections_added_in_page < max_sections_per_page):
section_text = WikiReader.text_replcaments(section_text)
section_words = parser.parse(section_text)
num_sections_added_in_page += self._add_section(page_name, page_name_words, section_name, section_name_words, section_in_page, section_words)
end_time = time.time()
print 'read_wiki total time = %.1f secs.' % (end_time-start_time)
print 'Read %d lines, %d pages, %d sections; applied action on %d sections' % (num_lines, self.num_pages, self.num_sections, self.num_section_action)
self._end_action()
return self._locdic
class HtmlReader(CorpusReader):
'''
HtmlReader - read an HTML corpus
'''
RE_SUBSTITUTE = [re.compile(rk) for rk in ['<img [^>]*alt="([^\"]*)"[^>]*>']]
RE_REMOVE = [re.compile(rr) for rr in ['<a [^>]+>[^<]*<[\/]a>', '<a [^>]+>\s*<strong>[^<]*<[\/]strong>\s*<[\/]a>',
'<[^>]*>', 'http[\:][^\"\>]+[\"\> ]']]
RE_REPLACE = [(re.compile(rr),rs) for rr,rs in [
('‘', "'"), ('’', "'"), ('“', '"'), ('”', '"'),
('"', '"'), ('‘', "'"), ('’', "'"), ('“', '"'), ('”', '"'),
('‎', '.'), (' ', '.'), ('…', ' ... '),
('—', ' - '), ('–', ' - '), ('−', ' - '),
('→', ' - '), ('←', ' - '), ('↔', ' - '), ('#8595;', ' - '), ('↑', ' - '), # various arrows
('≤', ' '), # <=
('≡', ' '), # = with 3 lines
('˚', ' degrees '),
(' ', ' '), ('°', ' degrees '), ('​', ''), ('☺', ''),
('&', '&'), ('•', ' '), ('◦', ' '), ('∙', ' '), ('‣', ' '), ('⁃', ' '), ('°', ' degrees '), ('∞', ' infinity '),
('$', '$'), ('€', ' euro '), ('£', ' pound '), ('¥', ' yen '), ('¢', ' cent '),
('©', ' '), ('®', ' '), ('℗', ' '), ('™', ' '), ('℠', ' '),
('α', 'alpha'), ('β', 'beta'), ('γ', 'gamma'), ('δ', 'delta'), ('ε', 'epsilon'), ('ζ', 'zeta'),
('η', 'eta'), ('θ', 'theta'), ('ι', 'iota'), ('κ', 'kappa'), ('λ', 'lambda'), ('μ', 'mu'), ('ν', 'nu'),
('ξ', 'xi'), ('ο', 'omicron'), ('π', 'pi'), ('ρ', 'rho'), ('σ', 'sigma'), ('τ', 'tau'), ('υ', 'upsilon'),
('φ', 'phi'), ('χ', 'chi'), ('ψ', 'psi'), ('ω', 'omega'), ('Α', 'Alpha'), ('Β', 'Beta'), ('Γ', 'Gamma'),
('Δ', 'Delta'), ('Ε', 'Epsilon'), ('Ζ', 'Zeta'), ('Η', 'Eta'), ('Θ', 'Theta'), ('Ι', 'Iota'), ('Κ', 'Kappa'),
('Λ', 'Lambda'), ('Μ', 'Mu'), ('Ν', 'Nu'), ('Ξ', 'Xi'), ('Ο', 'Omicron'), ('Π', 'Pi'), ('Ρ', 'Rho'),
('Σ', 'Sigma'), ('Τ', 'Tau'), ('Υ', 'Upsilon'), ('Φ', 'Phi'), ('Χ', 'Chi'), ('Ψ', 'Psi'), ('Ω', 'Omega'),
('º', ' '), ('´', '`'),
('½', ' 1/2'), ('¼', '1/4'), ('¾', '3/4'),
('µ', 'm'), ('ī', 'i'), ('ō', 'o'), ('ā', 'a'),
('×', '*'), ('•', '*'), ('·', '*'), ('÷', '/')] +
[('&#%3d;'%x,'A') for x in range(192,199)] + [('&#%3d;'%x,'C') for x in range(199,200)] + [('&#%3d;'%x,'E') for x in range(200,204)] +
[('&#%3d;'%x,'I') for x in range(204,208)] + [('&#%3d;'%x,'D') for x in range(208,209)] + [('&#%3d;'%x,'N') for x in range(209,210)] +
[('&#%3d;'%x,'O') for x in range(210,215)+[216]] + [('&#%3d;'%x,'U') for x in range(217,221)] + [('&#%3d;'%x,'Y') for x in range(221,222)] +
[('&#%3d;'%x,'S') for x in range(223,224)] + [('&#%3d;'%x,'a') for x in range(224,231)] + [('&#%3d;'%x,'c') for x in range(231,232)] +
[('&#%3d;'%x,'e') for x in range(232,236)] + [('&#%3d;'%x,'i') for x in range(236,240)] + [('&#%3d;'%x,'n') for x in range(241,242)] +
[('&#%3d;'%x,'o') for x in range(242,247)+[248]] + [('&#%3d;'%x,'u') for x in range(249,253)] + [('&#%3d;'%x,'y') for x in [253,255]]
]
@staticmethod
def parse_text(text):
for rk in HtmlReader.RE_SUBSTITUTE:
found = True
while found:
rkm = re.search(rk, text)
if rkm is None:
found = False
else:
text = text[:rkm.start()] + rkm.groups(0)[0] + text[rkm.end():]
for rr in HtmlReader.RE_REMOVE:
text = re.sub(rr, ' ', text)
for rr,rs in HtmlReader.RE_REPLACE:
text = re.sub(rr, rs, text)
return text
def read(self, htmldir, outfile, stop_words=set(), pos_words=set(), page_name_word_sets=None, corpus_words=None,
page_title_regexps=['<h1[^>]*>([^<]+)<[\/]h1>', '<table [^>]*>\s*<caption>([^<]+)<[\/]caption>', '<table [^>]*>\s*<caption>\s*<strong>([^<]+)<[\/]strong>\s*<[\/]caption>', '<table title="([^\"]+)"[^>]*>'],
page_title_ignore_suffixes=['-1', '-2', '- Advanced'],
ignore_sections=set(), section_regexp='<h[1-4][^>]*>([^<]+)<[\/]h[1-4]>',
min_pos_words_in_page_name=0, min_pos_words_in_section=0,
use_all_pages_match_pos_word=False, use_all_pages_match_sets=False, always_use_first_section=False,
action='write'):
self._reset(outfile=outfile, stop_words=stop_words, pos_words=pos_words, page_name_word_sets=page_name_word_sets, corpus_words=corpus_words,
min_pos_words_in_page_name=min_pos_words_in_page_name, min_pos_words_in_section=min_pos_words_in_section,
use_all_pages_match_pos_word=use_all_pages_match_pos_word, use_all_pages_match_sets=use_all_pages_match_sets,
always_use_first_section=always_use_first_section,
action=action)
parser = SimpleWordParser(tolower=True, ascii_conversion=True, ignore_special_words=False)
section_re = re.compile(section_regexp)
self._start_action()
page_name, section_name, section_in_page = None, None, 0
page_name_words, section_words = [], []
start_time = time.time()
filenames = ['%s/%s'%(htmldir,fname) for fname in os.listdir(htmldir) if fname.endswith('.html')]
assert len(filenames)>0
for ifname,fname in enumerate(filenames):
print 'Reading %s' % fname
# if fname!='C:/Chaim/chaim_private/Kaggle/AI2/corpus/CK12/OEBPS/table_66-1.html': continue
with open (fname, 'rb') as myfile:
text = myfile.read()
# page_name = fname[:-5] if fname.endswith('.html') else fname
pn_match = None
for ptr in page_title_regexps:
pn_match = re.search(ptr, text)
if pn_match is not None: break
if pn_match is None:
print 'Could not find page title in file %s - skipping' % fname
continue
page_name = pn_match.groups(0)[0].strip()
for ptis in page_title_ignore_suffixes:
if page_name.endswith(ptis):
page_name = page_name[:-len(ptis)]
break
page_name = HtmlReader.parse_text(page_name)
text = text[pn_match.end():]
page_name_words = parser.parse(page_name)
page_name = CorpusReader.part_name_from_words(page_name_words, ifname)
print 'page name = %s' % page_name
self._add_page(page_name, page_name_words)
parts = re.split(section_re, text)
assert len(parts)%2==1
# print 'Found %d parts/section-names: %s' % (len(parts), parts[:5])
parts = [''] + parts # 1st section has no name
for ipart in range(0,len(parts),2):
# print 'ipart %s' % ipart
if parts[ipart] is None:
section_name = ''
else:
section_name = parts[ipart].strip().lower()
section_name = HtmlReader.parse_text(section_name)
text = parts[ipart+1]
if np.any([(re.match(isr, section_name) is not None) for isr in ignore_sections]):
# print '----- ignoring section %s' % section_name
continue
section_name_words = parser.parse(section_name)
section_in_page = (ipart - 1) / 2
# print 'section <%s>' % section_name
# print 'text: %s' % text
text = HtmlReader.parse_text(text)
words = parser.parse(text)
section_words = words
# print 'words: %s' % section_words
self._add_section(page_name, page_name_words, section_name, section_name_words, section_in_page, section_words)
end_time = time.time()
print 'read_html total time = %.1f secs.' % (end_time-start_time)
print 'Read %d pages, %d sections; applied action on %d sections' % (self.num_pages, self.num_sections, self.num_section_action)
self._end_action()
return self._locdic
class TextReader(CorpusReader):
'''
TextReader - read a "text" corpus
'''
def read(self, dir, outfile, stop_words=set(), pos_words=set(),
first_line_regexp='^CHAPTER',
ignore_sections=set(), section_end_regexp='^\s*$',
action='write'):
self._reset(outfile=outfile, stop_words=stop_words, pos_words=pos_words, page_name_word_sets=set(), corpus_words=None,
min_pos_words_in_page_name=0, min_pos_words_in_section=0,
use_all_pages_match_pos_word=True, use_all_pages_match_sets=True, always_use_first_section=False,
action=action)
parser = SimpleWordParser(tolower=True, ascii_conversion=True, ignore_special_words=False)
first_line_re = re.compile(first_line_regexp)
section_end_re = re.compile(section_end_regexp)
self._start_action()
page_name, section_name, section_in_page = None, None, 0
page_name_words, section_words = [], []
start_time = time.time()
filenames = ['%s/%s'%(dir,fname) for fname in os.listdir(dir) if fname.endswith('.text')]
assert len(filenames)>0
for ifname,fname in enumerate(filenames):
print 'Reading %s' % fname
page_name = fname[:-5]
page_name_words = []
print 'page name = %s' % page_name
self._add_page(page_name, page_name_words)
section_in_page = 0
section_name, section_name_words = '', []
with open (fname, 'rb') as myfile:
found_first_line = False
text = ''
for line in myfile:
line = line.strip()
# print 'LINE: "%s"' % line
if found_first_line:
if re.match(section_end_re, line) is not None:
# print '--- section ended ---'
# print '%s' % text
# Add previous section
section_words = parser.parse(text)
self._add_section(page_name, page_name_words, section_name, section_name_words, section_in_page, section_words)
section_in_page += 1
section_name, section_name_words = '', []
text = ''
else:
text += ' ' + line
else:
if re.match(first_line_re, line) is not None:
# print '===== found first line ====='