Skip to main content
 首页 » 编程设计

python之NLTK WordNetLemmatizer 将 "US"处理为 "u"

2024年11月24日19artech

如果您将单词 "US"(美国)输入 WordNetLemmatizer 进行预处理(变为 "us",即小写) 来自 nltk.stem 包,它被翻译成 "u"。例如:

from nltk.stem import WordNetLemmatizer 
lmtzr = WordNetLemmatizer() 
word = "US".lower()  #  "US" becomes "us" 
lemma = lmtzr.lemmatize(word) 
print(lemma)  # prints "u" 

我什至尝试使用 POS 标记对单词进行词形还原,根据 pos_tag( ) 包 nltk 中的函数。但是 'NNP' 是一个 wordnet.NOUN,这是词形还原器在处理单词时的默认行为。因此,lmtzr.lemmatize(word) 和 lmtz.lemmatize(word, wordnet.NOUN) 是相同的(其中 wordnet 是从包中导入的nltk.stem.wordnet).

关于如何解决这个问题的任何想法,除了使用 if 声明?

请您参考如下方法:

如果您查看 WordNetLemmatizer 的源代码

def lemmatize(self, word, pos=NOUN): 
    lemmas = wordnet._morphy(word, pos) 
    return min(lemmas, key=len) if lemmas else word 

wordnet._morphy 返回 ['us', 'u']

min(lemmas, key=len) 返回最短的单词 u

wordnet._morphy 使用名词规则,将结尾 "s" 替换为 ""。

这是替换列表

[('s', ''), ('ses','s'), ('ves','f'), ('xes', 'x'), ('zes','z'), ('切','ch'), ('她','嘘'), ('男人','男人'), ('ies', 'y')]

我看不到一条非常干净的出路。

1) 你可以写一个特殊的规则来排除所有大写的单词。

2) 或者你可以添加一行 us us

到文件 nltk_data/corpora/wordnet/noun.exc

3)你可以自己写一个函数来选择最长的单词(其他单词可能是错误的)

from nltk.corpus.reader.wordnet import NOUN 
from nltk.corpus import wordnet 
def lemmatize(word, pos=NOUN): 
    lemmas = wordnet._morphy(word, pos) 
    return max(lemmas, key=len) if lemmas else word