向Python模式单数化添加术语的好方法
我正在使用Python的一个库来获取英语名词的单数形式。
In [1]: from pattern.en import singularize
In [2]: singularize('patterns')
Out[2]: 'pattern'
In [3]: singularize('gases')
Out[3]: 'gase'
在第二个例子中,我通过定义来解决这个问题。
def my_singularize(strn):
'''
Return the singular of a noun. Add special cases to correct pattern generic rules.
'''
exceptionDict = {'gases':'gas','spectra':'spectrum','cross':'cross','nuclei':'nucleus'}
try:
return exceptionDict[strn]
except:
return singularize(strn)
有没有更好的方法来做到这一点,比如说把规则添加到这个库里,或者让exceptionDict
以某种方式变成这个库内部的东西?
1 个回答
5
正如评论中提到的,你最好使用词形还原来处理单词。这个功能是 nltk 词干提取模块的一部分。
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
test_words = ['gases', 'spectrum','cross','nuclei']
%timeit [wnl.lemmatize(wrd) for wrd in test_words]
10000 loops, best of 3: 60.5 µs per loop
和你的函数相比,
%timeit [my_singularize(wrd) for wrd in test_words]
1000 loops, best of 3: 162 µs per loop
nltk 的词形还原效果更好。