Check if string appears as its own word - Python

前端 未结 4 456
生来不讨喜
生来不讨喜 2021-01-23 15:55

Let\'s say that I am looking for the word \"or\". What I want is to check whether that word appears as a word or as a substring of another word.

E.g.

<
4条回答
  •  北海茫月
    2021-01-23 16:11

    You can use the nltk (Natural Language Toolkit) to split the sentence into words, and then check if some word exists with ==.

    NLTK Installation

    NLTK Package Download

    import nltk
    
    def checkword(sentence):
        words = nltk.word_tokenize(sentence)
        return any((True for word in words if word == "or"))
    
    print(checkword("Should be false for."))
    print(checkword("Should be true or."))
    

提交回复
热议问题