WordNetLemmatizer在没有显式指定词性标记时无法返回正确的词形还原结果 - Python NLTK

11

我正在对Ted数据集的转录文本进行词形还原。我注意到了一些奇怪的事情:并不是所有的单词都被进行了词形还原。

selected -> select

哪个是正确的。

然而,除非我明确输入“v”(动词)属性,否则 involved! -> involvehorsing! -> horse

在Python终端上,我得到了正确的输出,但在我的代码中没有。

>>> from nltk.stem import WordNetLemmatizer
>>> from nltk.corpus import wordnet
>>> lem = WordNetLemmatizer()
>>> lem.lemmatize('involved','v')
u'involve'
>>> lem.lemmatize('horsing','v')
u'horse'

相关的代码部分是这样的:

for l in LDA_Row[0].split('+'):
    w=str(l.split('*')[1])
    word=lmtzr.lemmatize(w)
    wordv=lmtzr.lemmatize(w,'v')
    print wordv, word
    # if word is not wordv:
    #   print word, wordv

整个代码在这里

问题是什么?


代码没有安装就无法运行...你能提取输入吗?比如LDA_Row长什么样? - rebeling
这是因为你的POS标签有误。顺便说一句,下次请尽量不要发布完整的代码,而是在代码中添加解释问题的意义片段,否则Stackoverflow用户可能会试图关闭问题,称其为“问题不清楚”或者是一个“我的代码无法工作”的问题 =) - alvas
1个回答

25

词形归并器需要正确的词性标记才能准确处理,如果使用默认设置的WordNetLemmatizer.lemmatize()方法,则默认标记为名词。请参见https://github.com/nltk/nltk/blob/develop/nltk/stem/wordnet.py#L39

为解决此问题,在执行词形归并之前,请始终对数据进行词性标注,例如:

>>> from nltk.stem import WordNetLemmatizer
>>> from nltk import pos_tag, word_tokenize
>>> wnl = WordNetLemmatizer()
>>> sent = 'This is a foo bar sentence'
>>> pos_tag(word_tokenize(sent))
[('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('foo', 'NN'), ('bar', 'NN'), ('sentence', 'NN')]
>>> for word, tag in pos_tag(word_tokenize(sent)):
...     wntag = tag[0].lower()
...     wntag = wntag if wntag in ['a', 'r', 'n', 'v'] else None
...     if not wntag:
...             lemma = word
...     else:
...             lemma = wnl.lemmatize(word, wntag)
...     print lemma
... 
This
be
a
foo
bar
sentence

请注意,'is -> be'的意思是。
>>> wnl.lemmatize('is')
'is'
>>> wnl.lemmatize('is', 'v')
u'be'

回答这个问题,可以用你提供的例子中的文字:

>>> sent = 'These sentences involves some horsing around'
>>> for word, tag in pos_tag(word_tokenize(sent)):
...     wntag = tag[0].lower()
...     wntag = wntag if wntag in ['a', 'r', 'n', 'v'] else None
...     lemma = wnl.lemmatize(word, wntag) if wntag else word
...     print lemma
... 
These
sentence
involve
some
horse
around

请注意,WordNetLemmatizer存在一些小问题: 此外,NLTK的默认POS标记器正在经历一些重大变化以提高准确性:

如果你需要一个开箱即用的词形还原解决方案,可以看看https://github.com/alvations/pywsd,我已经添加了一些try-except语句来捕获WordNet中不存在的单词,详情请见https://github.com/alvations/pywsd/blob/master/pywsd/utils.py#L66


1
非常感谢,帮了大忙! - FlyingAura
绝对正确!干杯!! - trazoM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接