Reputation: 501
I am sure this is easy
I have a function that I would like to check a block of text from an rss feed's description. The text is returned as a sting, in this example it is article_description, I then want to check the string for any of the words in my list in this example called detect.
At the moment this is just returning False
def test(article_description):
detect = ['would','you','scale']
text = article_description.split()
print (text)
print(type(text))
print(detect)
if detect in text:
print ('Success')
else:
print ('False')
def main():
article_description = 'This is my text with the word scale in it.'
test(article_description)
if (__name__ == '__main__'):
main()
I had started with this function below but that returns Exception has occurred: TypeError 'in ' requires string as left operand, not list
def test(article_description):
word = ['would','you','scale']
if word in article_description:
print ('success')
Upvotes: 0
Views: 98
Reputation: 566
The correct syntax is str in list
, you are writing list in str
. Change:
if detect in text:
With:
if text in detect:
Upvotes: 1
Reputation: 9494
You use in
operator, which can be used to search a string in a collection or string in string.
In your case, detect
is not a string so you can use it.
Try this code instead:
def test(article_description):
detect = ['would','you','scale']
text = article_description.split()
is_success = any([d in text for d in detect])
print("success" if is_success else "False")
Here, any
will return True
if at least one of the words of detect
exists in the text.
Upvotes: 2
Reputation: 819
You are checking if the list is in the string. You could loop over the items in the list and compare the values to the string itself. The code below will loop over each item in the list and check if it is in the string and will print the result.
def test(article_description):
detect = ['would','you','scale']
text = article_description.split()
for i in detect:
if i in text:
print ('Success')
else:
print ('False')
def main():
article_description = 'This is my text with the word scale in it.'
test(article_description)
if (__name__ == '__main__'):
main()
Upvotes: 2