【问题标题】:How to check to see if a string is contained in any english word?如何检查字符串是否包含在任何英文单词中?
【发布时间】:2017-05-29 01:33:19
【问题描述】:

关闭此链接:How to check if a word is an English word with Python?

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

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

【问题讨论】:

  • 链接问题的解决方案有什么问题?
  • 意思是如果我想检查一个字符串是否是一个英文单词,我想看看一个字符串是否是一个单词或者包含在任何单词中。
  • 您链接的问题为这篇文章提供了答案。其他答案的哪一部分不适合保证您发布同一问题的故意重复?
  • 这对我的问题有何回答? d.check("blackjack") 返回 true 但 d.check("lackjac") 返回 false,在函数中我希望它返回 true,因为它包含在一些英文单词中。

标签: python nlp pyenchant


【解决方案1】:

基于solution 链接的答案。

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

【讨论】:

  • 这在大多数情况下都有效,但可能会出现误报。字符串 "xylo" 就是一个例子。此函数将在建议的答案中返回False,因为没有类似于.suggest(string) 建议的"xylo" 的单词包含该字符串,但单词xylophone 包含该字符串。这个建议的答案只有在它返回 True 时才能被信任,但在它返回 False 时不能被信任
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2011-05-20
  • 1970-01-01
相关资源
最近更新 更多