0

关闭此链接:如何使用 Python 检查单词是否为英文单词?

是否有任何方法可以查看(在 python 中)是否在英语中的任何单词中包含一串字母?例如,fun(wat) 将返回 true,因为“water”是一个单词(我确信还有多个其他单词包含 wat),但 fun(wayterlx) 将返回 false,因为 wayterlx 不包含在任何英语单词中。(它本身不是一个词)

编辑:第二个示例:d.check("blackjack") 返回 true,但 d.check("lackjac") 返回 false,但在我正在寻找的函数中,它会返回 true,因为它包含在一些英文单词中。

4

1 回答 1

1

基于链接答案的解决方案。

Dict.suggest我们可以使用方法定义下一个效用函数

def is_part_of_existing_word(string, words_dictionary):
    suggestions = words_dictionary.suggest(string)
    return any(string in suggestion
               for suggestion in suggestions)

然后简单地

>>> import enchant
>>> english_dictionary = enchant.Dict("en")
>>> is_part_of_existing_word('wat', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('wate', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('way', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('wayt', words_dictionary=english_dictionary)
False
>>> is_part_of_existing_word('wayter', words_dictionary=english_dictionary)
False
>>> is_part_of_existing_word('wayterlx', words_dictionary=english_dictionary)
False
>>> is_part_of_existing_word('lackjack', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('ucumber', words_dictionary=english_dictionary)
True
于 2017-05-29T03:16:42.750 回答