Check if string appears as its own word - Python

前端 未结 4 454
生来不讨喜
生来不讨喜 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."))
    
    0 讨论(0)
  • 2021-01-23 16:29

    Use a regex.

    >>> import re
    >>> re.search(r'\bor\b', 'or')
    <_sre.SRE_Match object at 0x7f445333a5e0>
    >>> re.search(r'\bor\b', 'for')
    >>> 
    
    0 讨论(0)
  • 2021-01-23 16:33

    Create a checker with just a test if it is in the line

    def check_word_in_line(word, line):
        return " {} ".format(word) in line
    
    print(check_word_in_line("or", "I can go shopping or not")) //True
    print(check_word_in_line("or", "I can go shopping for shoes")) //False
    
    0 讨论(0)
  • 2021-01-23 16:36

    You can use a regular expression for this:

    import re
    
    def contains_word(text, word):
        return bool(re.search(r'\b' + re.escape(word) + r'\b', text))
    
    print(contains_word('or', 'or')) # True
    print(contains_word('for', 'or')) # False
    print(contains_word('to be or not to be', 'or')) # True
    
    0 讨论(0)
提交回复
热议问题