Search code examples
pythonnlppyenchant

How to check to see if a string is contained in any english word?


Going off of this link: How to check if a word is an English word with Python?

Is there any way to see (in python) if a string of letters is contained in any word in the English language? For example, fun(wat) would return true since "water" is a word (and I'm sure there are multiple other words that contain wat) but fun(wayterlx) would be false since wayterlx is not contained in any English word. (and it is not a word itself)

Edit: A second example: d.check("blackjack") returns true but d.check("lackjac") returns false, but in the function I am looking for it would return true since it is contained in some english word.


Solution

  • Based on solution to the linked answer.

    We can define next utility function using Dict.suggest method

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

    then simply

    >>> 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