-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy path__init__.py
More file actions
2788 lines (2417 loc) · 115 KB
/
__init__.py
File metadata and controls
2788 lines (2417 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#### PATTERN | TEXT | PARSER #######################################################################
# -*- coding: utf-8 -*-
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
####################################################################################################
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from builtins import str, bytes, dict, int
from builtins import map, zip, filter
from builtins import object, range
import os
import sys
import re
import string
import types
import json
import codecs
import operator
from io import open
from codecs import BOM_UTF8
BOM_UTF8 = BOM_UTF8.decode('utf-8')
from xml.etree import cElementTree
from itertools import chain
from collections import defaultdict
from math import log, sqrt
try:
MODULE = os.path.dirname(os.path.realpath(__file__))
except:
MODULE = ""
from pattern.text.tree import Tree, Text, Sentence, Slice, Chunk, PNPChunk, Chink, Word, table
from pattern.text.tree import SLASH, WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA, AND, OR
DEFAULT = "default"
from pattern.helpers import encode_string, decode_string
decode_utf8 = decode_string
encode_utf8 = encode_string
PUNCTUATION = ".,;:!?()\[]{}`'\"@#$^&*+-|=~_”—“"
def ngrams(string, n=3, punctuation=PUNCTUATION, continuous=False):
""" Returns a list of n-grams (tuples of n successive words) from the given string.
Alternatively, you can supply a Text or Sentence object.
With continuous=False, n-grams will not run over sentence markers (i.e., .!?).
Punctuation marks are stripped from words.
"""
def strip_punctuation(s, punctuation=set(punctuation)):
return [w for w in s if (isinstance(w, Word) and w.string or w) not in punctuation]
if n <= 0:
return []
if isinstance(string, list):
s = [strip_punctuation(string)]
if isinstance(string, str):
s = [strip_punctuation(s.split(" ")) for s in tokenize(string)]
if isinstance(string, Sentence):
s = [strip_punctuation(string)]
if isinstance(string, Text):
s = [strip_punctuation(s) for s in string]
if continuous:
s = [sum(s, [])]
g = []
for st in s:
#s = [None] + s + [None]
g.extend([tuple(st[i:i + n]) for i in range(len(st) - n + 1)])
return g
def split_document_by_delimeters(string, regexp="[.,!?;: ]", min_word_len=1, stopwords=None):
"""
:param string: input string (text document)
:return: list of words
"""
string = re.sub(r"(-\n)", "", string.lower())
string = re.sub(r"(\n)", " ", string)
words = re.split(regexp, string)
if not stopwords:
stopwords = []
return [word for word in words if len(word) > min_word_len and word not in stopwords]
def train_topmine_ngrammer(documents, threshhold=1, max_ngramm_len=3, min_word_len=2, regexp="[.,!?;: ]", stopwords=None):
"""
:param documents: list of documents, where each document is represented by a string or by a list of prepared words (ex. stemmed)
:return: trained ngrammer for text corpus
"""
splitted_docs = []
for doc in documents:
if isinstance(doc, str):
splitted_docs.append(split_document_by_delimeters(doc, regexp, min_word_len=min_word_len, stopwords=stopwords))
elif isinstance(doc, list):
splitted_docs.append(doc)
else:
print("Wrong document format")
ng = None
try:
ng = NGrammer(regexp=regexp)
ng.frequentPhraseMining(splitted_docs, threshhold=threshhold, max_ngramm_len=max_ngramm_len)
except Exception:
print('Exception occurred while training ngrammer for abstracts')
return ng
def topmine_ngramms(doc, ng, threshhold=1):
"""
:param doc: document from text corpus, represented by a list of words without delimeters
:param ng: trained ngramer for text corpus
:param threshhold: the hyperparameter
:return: dictionary of ngramms
"""
splitted_doc = split_document_by_delimeters(doc, ng.regexp)
extracted_terms = ng.ngramm(splitted_doc, threshhold=threshhold)[0]
terms_dict = defaultdict(int)
for term in extracted_terms:
terms_dict[term] += 1
return terms_dict
class NGrammer(object):
_phrase2freq = {}
_delimiters = None
_delimiters_regex = None
_lengthInWords = 0
def __init__(self, regexp):
self._phrase2freq = {}
self._delimiters = {}
self._delimiters_regex = []
self._lengthInWords = 0
self.regexp = regexp
@property
def delimiters(self):
return self._delimiters
@delimiters.setter
def delimiters(self, value):
self._delimiters = value
@property
def delimiters_regex(self):
return self._delimiters_regex
@delimiters_regex.setter
def delimiters_regex(self, value):
self._delimiters_regex = [re.compile(p) for p in value]
@property
def lengthInWords(self):
return self._lengthInWords
@lengthInWords.setter
def lengthInWords(self, value):
self._lengthInWords = value
def frequentPhraseMining(self, document_list, threshhold, max_ngramm_len=10):
""" Function for collecting phrases and its frequencies"""
n = 1
A = {}
for doc_id, doc in enumerate(document_list):
A[doc_id] = {n: range(len(doc) - 1)}
for w in doc:
self._phrase2freq.setdefault(w, 0)
self._phrase2freq[w] += 1
D = set(range(len(document_list)))
for n in range(2, max_ngramm_len + 1):
print("extracting {}-grams".format(n))
if not D:
break
to_remove = []
for doc_id in D:
doc = document_list[doc_id]
A[doc_id][n] = []
for i in A[doc_id][n - 1]:
if n == 2:
flag = False
flag2 = False
if doc[i] in self._delimiters:
flag = True
for p in self._delimiters_regex:
if re.match(p, doc[i]):
flag2 = True
break
if not flag2:
self._lengthInWords += 1
if flag or flag2:
continue
ngram = u'_'.join([doc[i + j] for j in range(n - 1)])
if self._phrase2freq.get(ngram, threshhold - 1) >= threshhold:
A[doc_id][n] += [i]
if A[doc_id][n]:
A[doc_id][n].remove(A[doc_id][n][-1])
if not A[doc_id][n]:
to_remove += [doc_id]
else:
for i in A[doc_id][n]:
if i + 1 in A[doc_id][n]:
ngram = u'_'.join([doc[i + j] for j in range(n)])
self._phrase2freq.setdefault(ngram, 0)
self._phrase2freq[ngram] += 1
for r in to_remove:
D.remove(r)
def _significanceScore(self, ngramm1, ngramm2):
mu0 = float(self._phrase2freq.get(ngramm1, 0) *
self._phrase2freq.get(ngramm2, 0))
mu0 /= self._lengthInWords
f12 = float(self._phrase2freq.get(ngramm1 + u'_' + ngramm2, 0))
return (f12 - mu0) / sqrt(f12 + 1)
def ngramm(self, token_list, threshhold, indexes=[]):
H = []
res = [[i] for i in range(len(token_list))]
for i in range(len(res) - 1):
p1 = u'_'.join([token_list[w_i] for w_i in res[i]])
p2 = u'_'.join([token_list[w_i] for w_i in res[i + 1]])
score = self._significanceScore(p1, p2)
H += [score]
while len(res) > 1:
Best = max(H)
best_ind = H.index(Best)
if Best > threshhold:
new_res = res[:best_ind]
new_res += [res[best_ind] + res[best_ind + 1]]
new_res += res[best_ind + 2:]
if best_ind == 0:
new_H = []
else:
new_H = H[:best_ind - 1]
p1 = u'_'.join([token_list[w_i] for w_i in new_res[best_ind - 1]])
p2 = u'_'.join([token_list[w_i] for w_i in new_res[best_ind]])
new_H += [self._significanceScore(p1, p2)]
if best_ind != len(new_res) - 1:
p1 = u'_'.join([token_list[w_i] for w_i in new_res[best_ind]])
p2 = u'_'.join([token_list[w_i] for w_i in new_res[best_ind + 1]])
new_H += [self._significanceScore(p1, p2)]
new_H += H[best_ind + 2:]
H = new_H
res = new_res
else:
break
ngrammed_doc = []
for ngramm_ind in res:
ngrammed_doc.append(u'_'.join([token_list[x] for x in ngramm_ind]))
new_indexes = []
if indexes:
for i, ngramm_ind in enumerate(res):
new_indexes += []
start_ind = indexes[2 * ngramm_ind[0]]
length = indexes[2 * ngramm_ind[-1]] + indexes[2 * ngramm_ind[-1] + 1] - start_ind
new_indexes += (start_ind, length)
return ngrammed_doc, new_indexes
def removeDelimiters(self, ngramm_list, indexes=[]):
new_list = []
new_indexes = []
for i, w in enumerate(ngramm_list):
if w in self._delimiters:
continue
flag = False
for ptrn in self._delimiters_regex:
if re.match(ptrn, w):
flag = True
break
if flag:
continue
new_list.append(w)
if indexes:
new_indexes += (indexes[2 * i], indexes[2 * i + 1])
return new_list, new_indexes
def saveAsJson(self, filename, with_delimiters=False):
to_save = {u'lengthInWords': self._lengthInWords,
u'phrase2freq': self._phrase2freq}
if (with_delimiters):
to_save[u'delimiters'] = self._delimiters
to_save[u'delimiters_regex'] = [x.pattern for x in self._delimiters_regex]
with open(filename, 'w') as fp:
json.dump(to_save, fp)
def loadFromJson(self, filename, with_delimiters=False):
with open(filename, 'r') as fp:
loaded = json.load(fp)
self._lengthInWords = loaded[u'lengthInWords']
self._phrase2freq = loaded[u'phrase2freq']
if (with_delimiters):
self._delimiters = loaded[u'delimiters']
self._delimiters_regex = [re.compile(p) for p in loaded[u'delimiters_regex']]
FLOODING = re.compile(r"((.)\2{2,})", re.I) # ooo, xxx, !!!, ...
def deflood(s, n=3):
""" Returns the string with no more than n repeated characters, e.g.,
deflood("NIIIICE!!", n=1) => "Nice!"
deflood("nice.....", n=3) => "nice..."
"""
if n == 0:
return s[0:0]
return re.sub(r"((.)\2{%s,})" % (n - 1), lambda m: m.group(1)[0] * n, s)
def decamel(s, separator="_"):
""" Returns the string with CamelCase converted to underscores, e.g.,
decamel("TomDeSmedt", "-") => "tom-de-smedt"
decamel("getHTTPResponse2) => "get_http_response2"
"""
s = re.sub(r"([a-z0-9])([A-Z])", "\\1%s\\2" % separator, s)
s = re.sub(r"([A-Z])([A-Z][a-z])", "\\1%s\\2" % separator, s)
s = s.lower()
return s
def pprint(string, token=[WORD, POS, CHUNK, PNP], column=4):
""" Pretty-prints the output of Parser.parse() as a table with outlined columns.
Alternatively, you can supply a tree.Text or tree.Sentence object.
"""
if isinstance(string, str):
print("\n\n".join([table(sentence, fill=column) for sentence in Text(string, token)]))
if isinstance(string, Text):
print("\n\n".join([table(sentence, fill=column) for sentence in string]))
if isinstance(string, Sentence):
print(table(string, fill=column))
#--- LAZY DICTIONARY -------------------------------------------------------------------------------
# A lazy dictionary is empty until one of its methods is called.
# This way many instances (e.g., lexicons) can be created without using memory until used.
class lazydict(dict):
def load(self):
# Must be overridden in a subclass.
# Must load data with dict.__setitem__(self, k, v) instead of lazydict[k] = v.
pass
def _lazy(self, method, *args):
""" If the dictionary is empty, calls lazydict.load().
Replaces lazydict.method() with dict.method() and calls it.
"""
if dict.__len__(self) == 0:
self.load()
setattr(self, method, types.MethodType(getattr(dict, method), self))
return getattr(dict, method)(self, *args)
def __repr__(self):
return self._lazy("__repr__")
def __len__(self):
return self._lazy("__len__")
def __iter__(self):
return self._lazy("__iter__")
def __contains__(self, *args):
return self._lazy("__contains__", *args)
def __getitem__(self, *args):
return self._lazy("__getitem__", *args)
def __setitem__(self, *args):
return self._lazy("__setitem__", *args)
def __delitem__(self, *args):
return self._lazy("__delitem__", *args)
def setdefault(self, *args):
return self._lazy("setdefault", *args)
def get(self, *args, **kwargs):
return self._lazy("get", *args)
def items(self):
return self._lazy("items")
def keys(self):
return self._lazy("keys")
def values(self):
return self._lazy("values")
def update(self, *args):
return self._lazy("update", *args)
def pop(self, *args):
return self._lazy("pop", *args)
def popitem(self, *args):
return self._lazy("popitem", *args)
#--- LAZY LIST -------------------------------------------------------------------------------------
class lazylist(list):
def load(self):
# Must be overridden in a subclass.
# Must load data with list.append(self, v) instead of lazylist.append(v).
pass
def _lazy(self, method, *args):
""" If the list is empty, calls lazylist.load().
Replaces lazylist.method() with list.method() and calls it.
"""
if list.__len__(self) == 0:
self.load()
setattr(self, method, types.MethodType(getattr(list, method), self))
return getattr(list, method)(self, *args)
def __repr__(self):
return self._lazy("__repr__")
def __len__(self):
return self._lazy("__len__")
def __iter__(self):
return self._lazy("__iter__")
def __contains__(self, *args):
return self._lazy("__contains__", *args)
def __getitem__(self, *args):
return self._lazy("__getitem__", *args)
def __setitem__(self, *args):
return self._lazy("__setitem__", *args)
def __delitem__(self, *args):
return self._lazy("__delitem__", *args)
def insert(self, *args):
return self._lazy("insert", *args)
def append(self, *args):
return self._lazy("append", *args)
def extend(self, *args):
return self._lazy("extend", *args)
def remove(self, *args):
return self._lazy("remove", *args)
def pop(self, *args):
return self._lazy("pop", *args)
def index(self, *args):
return self._lazy("index", *args)
def count(self, *args):
return self._lazy("count", *args)
#--- LAZY SET --------------------------------------------------------------------------------------
class lazyset(set):
def load(self):
# Must be overridden in a subclass.
# Must load data with list.append(self, v) instead of lazylist.append(v).
pass
def _lazy(self, method, *args):
""" If the list is empty, calls lazylist.load().
Replaces lazylist.method() with list.method() and calls it.
"""
print("!")
if set.__len__(self) == 0:
self.load()
setattr(self, method, types.MethodType(getattr(set, method), self))
return getattr(set, method)(self, *args)
def __repr__(self):
return self._lazy("__repr__")
def __len__(self):
return self._lazy("__len__")
def __iter__(self):
return self._lazy("__iter__")
def __contains__(self, *args):
return self._lazy("__contains__", *args)
def __sub__(self, *args):
return self._lazy("__sub__", *args)
def __and__(self, *args):
return self._lazy("__and__", *args)
def __or__(self, *args):
return self._lazy("__or__", *args)
def __xor__(self, *args):
return self._lazy("__xor__", *args)
def __isub__(self, *args):
return self._lazy("__isub__", *args)
def __iand__(self, *args):
return self._lazy("__iand__", *args)
def __ior__(self, *args):
return self._lazy("__ior__", *args)
def __ixor__(self, *args):
return self._lazy("__ixor__", *args)
def __gt__(self, *args):
return self._lazy("__gt__", *args)
def __lt__(self, *args):
return self._lazy("__lt__", *args)
def __gte__(self, *args):
return self._lazy("__gte__", *args)
def __lte__(self, *args):
return self._lazy("__lte__", *args)
def add(self, *args):
return self._lazy("add", *args)
def pop(self, *args):
return self._lazy("pop", *args)
def remove(self, *args):
return self._lazy("remove", *args)
def discard(self, *args):
return self._lazy("discard", *args)
def isdisjoint(self, *args):
return self._lazy("isdisjoint", *args)
def issubset(self, *args):
return self._lazy("issubset", *args)
def issuperset(self, *args):
return self._lazy("issuperset", *args)
def union(self, *args):
return self._lazy("union", *args)
def intersection(self, *args):
return self._lazy("intersection", *args)
def difference(self, *args):
return self._lazy("difference", *args)
#### PARSER ########################################################################################
# Pattern's text parsers are based on Brill's algorithm, or optionally on a trained language model.
# Brill's algorithm automatically acquires a lexicon of known words (aka tag dictionary),
# and a set of rules for tagging unknown words from a training corpus.
# Morphological rules are used to tag unknown words based on word suffixes (e.g., -ly = adverb).
# Contextual rules are used to tag unknown words based on a word's role in the sentence.
# Named entity rules are used to annotate proper nouns (NNP's: Google = NNP-ORG).
# When available, the parser will use a faster and more accurate language model (SLP, SVM, NB, ...).
#--- LEXICON ---------------------------------------------------------------------------------------
def _read(path, encoding="utf-8", comment=";;;"):
""" Returns an iterator over the lines in the file at the given path,
strippping comments and decoding each line to Unicode.
"""
if path:
if isinstance(path, str) and os.path.exists(path):
# From file path.
f = open(path, "r", encoding="utf-8")
elif isinstance(path, str):
# From string.
f = path.splitlines()
else:
# From file or buffer.
f = path
for i, line in enumerate(f):
line = line.strip(BOM_UTF8) if i == 0 and isinstance(line, str) else line
line = line.strip()
line = decode_utf8(line, encoding)
if not line or (comment and line.startswith(comment)):
continue
yield line
raise StopIteration
class Lexicon(lazydict):
def __init__(self, path=""):
""" A dictionary of known words and their part-of-speech tags.
"""
self._path = path
@property
def path(self):
return self._path
def load(self):
# Arnold NNP x
dict.update(self, (x.split(" ")[:2] for x in _read(self._path) if len(x.split(" ")) > 1))
#--- FREQUENCY -------------------------------------------------------------------------------------
class Frequency(lazydict):
def __init__(self, path=""):
""" A dictionary of words and their relative document frequency.
"""
self._path = path
@property
def path(self):
return self._path
def load(self):
# and 0.4805
for x in _read(self.path):
x = x.split()
dict.__setitem__(self, x[0], float(x[1]))
#--- LANGUAGE MODEL --------------------------------------------------------------------------------
# A language model determines the statistically most probable tag for an unknown word.
# A pattern.vector Classifier such as SLP can be used to produce a language model,
# by generalizing patterns from a treebank (i.e., a corpus of hand-tagged texts).
# For example:
# "generalizing/VBG from/IN patterns/NNS" and
# "dancing/VBG with/IN squirrels/NNS"
# both have a pattern -ing/VBG + [?] + NNS => IN.
# Unknown words preceded by -ing and followed by a plural noun will be tagged IN (preposition),
# unless (put simply) a majority of other patterns learned by the classifier disagrees.
class Model(object):
def __init__(self, path="", classifier=None, known=set(), unknown=set()):
""" A language model using a classifier (e.g., SLP, SVM) trained on morphology and context.
"""
try:
from pattern.vector import Classifier
from pattern.vector import Perceptron
except ImportError:
sys.path.insert(0, os.path.join(MODULE, ".."))
from vector import Classifier
from vector import Perceptron
self._path = path
# Use a property instead of a subclass, so users can choose their own classifier.
self._classifier = Classifier.load(path) if path else classifier or Perceptron()
# Parser.lexicon entries can be ambiguous (e.g., about/IN is RB 25% of the time).
# Parser.lexicon entries also in Model.unknown are overruled by the model.
# Parser.lexicon entries also in Model.known are not learned by the model
# (only their suffix and context is learned, see Model._v() below).
self.unknown = unknown | self._classifier._data.get("model_unknown", set())
self.known = known
@property
def path(self):
return self._path
@classmethod
def load(self, path="", lexicon={}):
return Model(path, lexicon)
def save(self, path, final=True):
self._classifier._data["model_unknown"] = self.unknown
self._classifier.save(path, final) # final = unlink training data (smaller file).
def train(self, token, tag, previous=None, next=None):
""" Trains the model to predict the given tag for the given token,
in context of the given previous and next (token, tag)-tuples.
"""
self._classifier.train(self._v(token, previous, next), type=tag)
def classify(self, token, previous=None, next=None, **kwargs):
""" Returns the predicted tag for the given token,
in context of the given previous and next (token, tag)-tuples.
"""
return self._classifier.classify(self._v(token, previous, next), **kwargs)
def apply(self, token, previous=(None, None), next=(None, None)):
""" Returns a (token, tag)-tuple for the given token,
in context of the given previous and next (token, tag)-tuples.
"""
return [token[0], self._classifier.classify(self._v(token[0], previous, next))]
def _v(self, token, previous=None, next=None):
""" Returns a training vector for the given token and its context.
"""
def f(v, *s):
v[" ".join(s)] = 1
p, n = previous, next
p = ("", "") if not p else (p[0] or "", p[1] or "")
n = ("", "") if not n else (n[0] or "", n[1] or "")
v = {}
f(v, "b", "b") # Bias.
f(v, "h", token[:1]) # Capitalization.
f(v, "w", token[-6:] if token not in self.known or token in self.unknown else "")
f(v, "x", token[-3:]) # Word suffix.
f(v, "-x", p[0][-3:]) # Word suffix left.
f(v, "+x", n[0][-3:]) # Word suffix right.
f(v, "-t", p[1]) # Tag left.
f(v, "-+", p[1] + n[1]) # Tag left + right.
f(v, "+t", n[1]) # Tag right.
return v
def _get_description(self):
return self._classifier.description
def _set_description(self, s):
self._classifier.description = s
description = property(_get_description, _set_description)
#--- MORPHOLOGICAL RULES ---------------------------------------------------------------------------
# Brill's algorithm generates lexical (i.e., morphological) rules in the following format:
# NN s fhassuf 1 NNS x => unknown words ending in -s and tagged NN change to NNS.
# ly hassuf 2 RB x => unknown words ending in -ly change to RB.
class Morphology(lazylist):
def __init__(self, path="", known={}):
""" A list of rules based on word morphology (prefix, suffix).
"""
self.known = known
self._path = path
self._cmd = set((
"word", # Word is x.
"char", # Word contains x.
"haspref", # Word starts with x.
"hassuf", # Word end with x.
"addpref", # x + word is in lexicon.
"addsuf", # Word + x is in lexicon.
"deletepref", # Word without x at the start is in lexicon.
"deletesuf", # Word without x at the end is in lexicon.
"goodleft", # Word preceded by word x.
"goodright", # Word followed by word x.
))
self._cmd.update([("f" + x) for x in self._cmd])
@property
def path(self):
return self._path
def load(self):
# ["NN", "s", "fhassuf", "1", "NNS", "x"]
list.extend(self, (x.split() for x in _read(self._path)))
def apply(self, token, previous=(None, None), next=(None, None)):
""" Applies lexical rules to the given token, which is a [word, tag] list.
"""
w = token[0]
for r in self:
if r[1] in self._cmd: # Rule = ly hassuf 2 RB x
f, x, pos, cmd = bool(0), r[0], r[-2], r[1].lower()
if r[2] in self._cmd: # Rule = NN s fhassuf 1 NNS x
f, x, pos, cmd = bool(1), r[1], r[-2], r[2].lower().lstrip("f")
if f and token[1] != r[0]:
continue
if (cmd == "word" and x == w) \
or (cmd == "char" and x in w) \
or (cmd == "haspref" and w.startswith(x)) \
or (cmd == "hassuf" and w.endswith(x)) \
or (cmd == "addpref" and x + w in self.known) \
or (cmd == "addsuf" and w + x in self.known) \
or (cmd == "deletepref" and w.startswith(x) and w[len(x):] in self.known) \
or (cmd == "deletesuf" and w.endswith(x) and w[:-len(x)] in self.known) \
or (cmd == "goodleft" and x == next[0]) \
or (cmd == "goodright" and x == previous[0]):
token[1] = pos
return token
def insert(self, i, tag, affix, cmd="hassuf", tagged=None):
""" Inserts a new rule that assigns the given tag to words with the given affix,
e.g., Morphology.append("RB", "-ly").
"""
if affix.startswith("-") and affix.endswith("-"):
affix, cmd = affix[+1:-1], "char"
if affix.startswith("-"):
affix, cmd = affix[+1:-0], "hassuf"
if affix.endswith("-"):
affix, cmd = affix[+0:-1], "haspref"
if tagged:
r = [tagged, affix, "f" + cmd.lstrip("f"), tag, "x"]
else:
r = [affix, cmd.lstrip("f"), tag, "x"]
lazylist.insert(self, i, r)
def append(self, *args, **kwargs):
self.insert(len(self) - 1, *args, **kwargs)
def extend(self, rules=[]):
for r in rules:
self.append(*r)
#--- CONTEXT RULES ---------------------------------------------------------------------------------
# Brill's algorithm generates contextual rules in the following format:
# VBD VB PREVTAG TO => unknown word tagged VBD changes to VB if preceded by a word tagged TO.
class Context(lazylist):
def __init__(self, path=""):
""" A list of rules based on context (preceding and following words).
"""
self._path = path
self._cmd = set((
"prevtag", # Preceding word is tagged x.
"nexttag", # Following word is tagged x.
"prev2tag", # Word 2 before is tagged x.
"next2tag", # Word 2 after is tagged x.
"prev1or2tag", # One of 2 preceding words is tagged x.
"next1or2tag", # One of 2 following words is tagged x.
"prev1or2or3tag", # One of 3 preceding words is tagged x.
"next1or2or3tag", # One of 3 following words is tagged x.
"surroundtag", # Preceding word is tagged x and following word is tagged y.
"curwd", # Current word is x.
"prevwd", # Preceding word is x.
"nextwd", # Following word is x.
"prev1or2wd", # One of 2 preceding words is x.
"next1or2wd", # One of 2 following words is x.
"next1or2or3wd", # One of 3 preceding words is x.
"prev1or2or3wd", # One of 3 following words is x.
"prevwdtag", # Preceding word is x and tagged y.
"nextwdtag", # Following word is x and tagged y.
"wdprevtag", # Current word is y and preceding word is tagged x.
"wdnexttag", # Current word is x and following word is tagged y.
"wdand2aft", # Current word is x and word 2 after is y.
"wdand2tagbfr", # Current word is y and word 2 before is tagged x.
"wdand2tagaft", # Current word is x and word 2 after is tagged y.
"lbigram", # Current word is y and word before is x.
"rbigram", # Current word is x and word after is y.
"prevbigram", # Preceding word is tagged x and word before is tagged y.
"nextbigram", # Following word is tagged x and word after is tagged y.
))
@property
def path(self):
return self._path
def load(self):
# ["VBD", "VB", "PREVTAG", "TO"]
list.extend(self, (x.split() for x in _read(self._path)))
def apply(self, tokens):
""" Applies contextual rules to the given list of tokens,
where each token is a [word, tag] list.
"""
o = [("STAART", "STAART")] * 3 # Empty delimiters for look ahead/back.
t = o + tokens + o
for i, token in enumerate(t):
for r in self:
if token[1] == "STAART":
continue
if token[1] != r[0] and r[0] != "*":
continue
cmd, x, y = r[2], r[3], r[4] if len(r) > 4 else ""
cmd = cmd.lower()
if (cmd == "prevtag" and x == t[i - 1][1]) \
or (cmd == "nexttag" and x == t[i + 1][1]) \
or (cmd == "prev2tag" and x == t[i - 2][1]) \
or (cmd == "next2tag" and x == t[i + 2][1]) \
or (cmd == "prev1or2tag" and x in (t[i - 1][1], t[i - 2][1])) \
or (cmd == "next1or2tag" and x in (t[i + 1][1], t[i + 2][1])) \
or (cmd == "prev1or2or3tag" and x in (t[i - 1][1], t[i - 2][1], t[i - 3][1])) \
or (cmd == "next1or2or3tag" and x in (t[i + 1][1], t[i + 2][1], t[i + 3][1])) \
or (cmd == "surroundtag" and x == t[i - 1][1] and y == t[i + 1][1]) \
or (cmd == "curwd" and x == t[i + 0][0]) \
or (cmd == "prevwd" and x == t[i - 1][0]) \
or (cmd == "nextwd" and x == t[i + 1][0]) \
or (cmd == "prev1or2wd" and x in (t[i - 1][0], t[i - 2][0])) \
or (cmd == "next1or2wd" and x in (t[i + 1][0], t[i + 2][0])) \
or (cmd == "prevwdtag" and x == t[i - 1][0] and y == t[i - 1][1]) \
or (cmd == "nextwdtag" and x == t[i + 1][0] and y == t[i + 1][1]) \
or (cmd == "wdprevtag" and x == t[i - 1][1] and y == t[i + 0][0]) \
or (cmd == "wdnexttag" and x == t[i + 0][0] and y == t[i + 1][1]) \
or (cmd == "wdand2aft" and x == t[i + 0][0] and y == t[i + 2][0]) \
or (cmd == "wdand2tagbfr" and x == t[i - 2][1] and y == t[i + 0][0]) \
or (cmd == "wdand2tagaft" and x == t[i + 0][0] and y == t[i + 2][1]) \
or (cmd == "lbigram" and x == t[i - 1][0] and y == t[i + 0][0]) \
or (cmd == "rbigram" and x == t[i + 0][0] and y == t[i + 1][0]) \
or (cmd == "prevbigram" and x == t[i - 2][1] and y == t[i - 1][1]) \
or (cmd == "nextbigram" and x == t[i + 1][1] and y == t[i + 2][1]):
t[i] = [t[i][0], r[1]]
return t[len(o):-len(o)]
def insert(self, i, tag1, tag2, cmd="prevtag", x=None, y=None):
""" Inserts a new rule that updates words with tag1 to tag2,
given constraints x and y, e.g., Context.append("TO < NN", "VB")
"""
if " < " in tag1 and not x and not y:
tag1, x = tag1.split(" < ")
cmd = "prevtag"
if " > " in tag1 and not x and not y:
x, tag1 = tag1.split(" > ")
cmd = "nexttag"
lazylist.insert(self, i, [tag1, tag2, cmd, x or "", y or ""])
def append(self, *args, **kwargs):
self.insert(len(self) - 1, *args, **kwargs)
def extend(self, rules=[]):
for r in rules:
self.append(*r)
#--- NAMED ENTITY RECOGNIZER -----------------------------------------------------------------------
RE_ENTITY1 = re.compile(r"^http://") # http://www.domain.com/path
RE_ENTITY2 = re.compile(r"^www\..*?\.(com|org|net|edu|de|uk)$") # www.domain.com
RE_ENTITY3 = re.compile(r"^[\w\-\.\+]+@(\w[\w\-]+\.)+[\w\-]+$") # name@domain.com
class Entities(lazydict):
def __init__(self, path="", tag="NNP"):
""" A dictionary of named entities and their labels.
For domain names and e-mail adresses, regular expressions are used.
"""
self.tag = tag
self._path = path
self._cmd = ((
"pers", # Persons: George/NNP-PERS
"loc", # Locations: Washington/NNP-LOC
"org", # Organizations: Google/NNP-ORG
))
@property
def path(self):
return self._path
def load(self):
# ["Alexander", "the", "Great", "PERS"]
# {"alexander": [["alexander", "the", "great", "pers"], ...]}
for x in _read(self.path):
x = [x.lower() for x in x.split()]
dict.setdefault(self, x[0], []).append(x)
def apply(self, tokens):
""" Applies the named entity recognizer to the given list of tokens,
where each token is a [word, tag] list.
"""
# Note: we could also scan for patterns, e.g.,
# "my|his|her name is|was *" => NNP-PERS.
i = 0
while i < len(tokens):
w = tokens[i][0].lower()
if RE_ENTITY1.match(w) \
or RE_ENTITY2.match(w) \
or RE_ENTITY3.match(w):
tokens[i][1] = self.tag
if w in self:
for e in self[w]:
# Look ahead to see if successive words match the named entity.
e, tag = (e[:-1], "-" + e[-1].upper()) if e[-1] in self._cmd else (e, "")
b = True
for j, e in enumerate(e):
if i + j >= len(tokens) or tokens[i + j][0].lower() != e:
b = False
break
if b:
for token in tokens[i:i + j + 1]:
token[1] = token[1] if token[1].startswith(self.tag) else self.tag
token[1] += tag
i += j
break
i += 1
return tokens
def append(self, entity, name="pers"):
""" Appends a named entity to the lexicon,
e.g., Entities.append("Hooloovoo", "PERS")
"""
e = list(map(lambda s: s.lower(), entity.split(" ") + [name]))
self.setdefault(e[0], []).append(e)