如何检查字符串是否包含在任何英语单词中



离开这个链接:如何使用Python检查一个单词是否是英语单词?

有没有办法查看(在python中(英语中的任何单词中是否包含一串字母?例如,fun(wat( 会返回 true,因为"water"是一个单词(我敢肯定还有多个其他单词包含 wat(,但 fun(wayterlx( 是假的,因为 wayterlx 不包含在任何英语单词中。(它本身不是一个词(

编辑:第二个例子:d.check("二十一点"(返回true,

但d.check("lackjac"(返回false,但在我正在寻找的函数中,它将返回true,因为它包含在一些英语单词中。

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

我们可以使用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

最新更新