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

0 投票
1 回答
1943 浏览
提问于 2025-05-17 16:25

根据这个链接:如何用Python检查一个词是否是英语单词?

有没有办法在Python中检查一串字母是否包含在任何英语单词里?比如说,fun(wat)会返回真,因为“water”是一个单词(我相信还有很多其他单词也包含wat),但是fun(wayterlx)会返回假,因为wayterlx并不包含在任何英语单词中。(而且它本身也不是一个单词)

编辑:再举个例子:d.check("blackjack")返回真,但d.check("lackjac")返回假,但在我想要的那个函数中,它应该返回真,因为它包含在某个英语单词里。

相关问题:

  • 暂无相关问题
暂无标签

1 个回答

2

根据这个链接的解决方案

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

撰写回答