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.
<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."))
Use a regex.
>>> import re
>>> re.search(r'\bor\b', 'or')
<_sre.SRE_Match object at 0x7f445333a5e0>
>>> re.search(r'\bor\b', 'for')
>>>
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
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