如何用Python检查一个词是否是英语单词?

189 投票
12 回答
290133 浏览
提问于 2025-04-16 04:34

我想在一个Python程序里检查一个单词是否在英语词典中。

我觉得可以用nltk的wordnet接口来实现这个功能,但我不知道怎么用它来完成这么简单的任务。

def is_english_word(word):
    pass # how to I implement is_english_word?

is_english_word(token.lower())

将来,我可能还想检查一个单词的单数形式是否在词典里(比如,properties -> property -> 英语单词)。我该怎么做呢?

12 个回答

53

使用NLTK:

from nltk.corpus import wordnet

if not wordnet.synsets(word_to_test):
  #Not an English Word
else:
  #English Word

如果你在安装wordnet时遇到问题,或者想尝试其他方法,可以参考这篇文章

77

这个方法和WordNet配合得不好,因为WordNet并不包含所有的英语单词。还有一种基于NLTK的方法,不需要使用enchant,就是使用NLTK的单词库。

>>> from nltk.corpus import words
>>> "would" in words.words()
True
>>> "could" in words.words()
True
>>> "should" in words.words()
True
>>> "I" in words.words()
True
>>> "you" in words.words()
True
281

如果你想要更强大和灵活的拼写检查功能,可以使用一个专门的拼写检查库,比如PyEnchant。这里有一个教程,或者你也可以直接开始使用:

>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
>>>

PyEnchant自带了一些字典(比如英式英语、美国英语、德语和法语),如果你需要更多语言的话,还可以使用任何OpenOffice提供的字典。

还有一个叫做inflect的库,似乎是用来处理复数形式的,但我不太清楚它的效果如何。

撰写回答