-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
linguist.py
320 lines (289 loc) · 7.86 KB
/
linguist.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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#======================================================================
#
# linguist.py -
#
# Created by skywind on 2017/03/22
# Last change: 2017/03/22 13:44:42
#
#======================================================================
import sys, os, time
# https://www.nodebox.net/code/index.php/Linguistics
#----------------------------------------------------------------------
# python 2/3 compatible
#----------------------------------------------------------------------
if sys.version_info[0] >= 3:
long = int
xrange = range
unicode = str
#----------------------------------------------------------------------
# 词形变换
#----------------------------------------------------------------------
class WordHelper (object):
# 初始化
def __init__ (self):
self.__lemmatizer = None
# 取得 WordNet 的词定义
def definition (self, word, txt = False):
from nltk.corpus import wordnet as wn
syns = wn.synsets(word)
output = []
for syn in syns:
name = syn.name()
part = name.split('.')
mode = part[1]
output.append((mode, syn.definition()))
if txt:
output = '\n'.join([ (m + ' ' + n) for m, n in output ])
return output
# 取得动词的:-ing, -ed, -en, -s
# NodeBox 的 Linguistics 软件包 11487 个动词只能处理 6722 个
def verb_tenses (self, word):
word = word.lower()
if ' ' in word:
return None
import en
if not en.is_verb(word):
return None
tenses = {}
try:
tenses['i'] = en.verb.present_participle(word)
tenses['p'] = en.verb.past(word)
tenses['d'] = en.verb.past_participle(word)
tenses['3'] = en.verb.present(word, person = 3, negate = False)
except:
return None
valid = True
for k in tenses:
v = tenses[k]
if not v:
valid = False
break
elif "'" in v:
valid = False
break
if not valid:
return None
return tenses
# 名词的复数:有时候不可数名词也会被加上 -s,需要先判断是否可数(语料库)
def noun_plural (self, word, method = 0):
plural = None
if method == 0:
import en
plural = en.noun.plural(word)
elif method == 1:
import pattern.en
plural = pattern.en.pluralize(word)
elif method == 2:
import inflect
plural = inflect.pluralize(word)
elif method < 0:
plural = self.noun_plural(word, 0)
if not plural:
plural = self.noun_plural(word, 1)
if not plural:
try:
import inflect
plural = inflect.pluralize(word)
except:
pass
if not plural:
return None
return plural
# 求解比较级
def adjective_comparative (self, word):
import pattern.en
return pattern.en.comparative(word)
# 求解最高级
def adjective_superlative (self, word):
import pattern.en
return pattern.en.superlative(word)
# 求解复数,使用 pattern.en 软件包
def pluralize (self, word):
import pattern.en
return pattern.en.pluralize(word)
# 取得所有动词
def all_verbs (self):
import en
words = []
for n in en.wordnet.all_verbs():
words.append(n.form)
return words
# 取得所有副词
def all_adverbs (self):
import en
words = []
for n in en.wordnet.all_adverbs():
words.append(n.form)
return words
# 取得所有形容词
def all_adjectives (self):
import en
words = []
for n in en.wordnet.all_adjectives():
words.append(n.form)
return words
# 取得所有名词
def all_nouns (self):
import en
words = []
for n in en.wordnet.all_nouns():
words.append(n.form)
return words
# 返回原始单词
def lemmatize (self, word, pos = 'n'):
word = word.lower()
if self.__lemmatizer is None:
from nltk.stem.wordnet import WordNetLemmatizer
self.__lemmatizer = WordNetLemmatizer()
return self.__lemmatizer.lemmatize(word, pos)
#----------------------------------------------------------------------
# global
#----------------------------------------------------------------------
tools = WordHelper()
#----------------------------------------------------------------------
# WordRoot
#----------------------------------------------------------------------
class WordRoot (object):
def __init__ (self, root):
self.root = root
self.count = 0
self.words = {}
def add (self, c5, word, n = 1):
if c5 and word:
term = (c5, word)
if not term in self.words:
self.words[term] = n
else:
self.words[term] += n
self.count += n
return True
def dump (self):
output = []
for term in self.words:
c5, word = term
output.append((c5, word, self.words[term]))
output.sort(key = lambda x: (x[2], x[0]), reverse = True)
return output
def __len__ (self):
return len(self.words)
def __getitem__ (self, key):
return self.words[key]
#----------------------------------------------------------------------
# testing
#----------------------------------------------------------------------
if __name__ == '__main__':
def test1():
for word in ['was', 'gave', 'be', 'bound']:
print('%s -> %s'%(word, tools.lemmatize(word, 'v')))
return 0
def test2():
import ascmini
rows = ascmini.csv_load('bnc-words.csv')
output = []
words = {}
for row in rows:
root = row[0]
size = int(row[1])
c5 = row[2]
word = row[3]
count = int(row[4])
head = root[:1].lower()
if size <= 1:
continue
if count * 1000 / size < 1:
continue
if '*' in word:
continue
if c5 in ('UNC', 'CRD'):
continue
if '(' in root or '/' in root:
continue
if head != '\'' and (not head.isalpha()):
if head.isdigit():
continue
if head in ('$', '#', '-'):
continue
if root.count('\'') >= 2:
continue
if not root in words:
stem = WordRoot(root)
words[root] = stem
else:
stem = words[root]
stem.add(c5, word.lower(), count)
for key in words:
stem = words[key]
for c5, word, count in stem.dump():
output.append((stem.root, stem.count, c5, word, count))
output.sort(key = lambda x: (x[1], x[0]), reverse = True)
# ascmini.csv_save(output, 'bnc-clear.csv')
print 'count', len(words)
def test3():
import ascmini
rows = ascmini.csv_load('bnc-clear.csv')
output = []
words = {}
for row in rows:
root = row[0]
size = int(row[1])
c5 = row[2]
word = row[3].lower()
count = int(row[4])
if word == root:
continue
if not root in words:
stem = WordRoot(root)
words[root] = stem
else:
stem = words[root]
stem.add('*', word, count)
stem.count = size
fp = open('bnc-lemma.txt', 'w')
lemmas = []
for key in words:
stem = words[key]
part = []
for c5, word, count in stem.dump():
output.append((stem.root, stem.count, c5, word, count))
part.append('%s/%d'%(word, count))
if not part:
continue
text = '%s/%d -> '%(stem.root, stem.count)
lemmas.append((stem.count, stem.root, text + ','.join(part)))
output.sort(key = lambda x: (x[1], x[0]), reverse = True)
lemmas.sort(reverse = True)
for _, _, text in lemmas:
fp.write(text + '\n')
ascmini.csv_save(output, 'bnc-test.csv')
print 'count', len(words)
return 0
def test4():
import stardict
lm1 = stardict.LemmaDB()
lm2 = stardict.LemmaDB()
lm1.load('bnc-lemma.txt')
lm2.load('lemma.en.txt')
count1 = 0
count2 = 0
for stem in lm2.dump('stem'):
childs = lm2.get(stem)
stem = stem.lower()
if len(stem) <= 2 and stem.isupper():
continue
if not stem in lm1:
count1 += 1
else:
obj = lm1.get(stem)
for word in childs:
word = word.lower()
if not word in obj:
print '%s -> %s'%(stem, word)
count2 += 1
for word in childs:
lm1.add(stem, word.lower())
print 'count', count1, count2
lm1.save('lemma-bnc.txt')
return 0
test4()