'How to detect certain words from a given string in Python?
I'm making a basic program to detect certain words from a string and mark the message as SPAM if the string contains the spam keywords but ran into a problem. The compiler doesn't detect it as spam unless I input the exact same strings.
Here's the code :
text = input("text : ")
if(text == 'make a lot of money' in text) or (text == 'buy now'in text) or (text == 'subscribe this 'in text) or (text =='click link' in text):
print("SPAM")
else:
print("OKAY")
Solution 1:[1]
You're not using correct syntax for if statement, please use this:
text = input("text : ")
if 'make a lot of money' in text or 'buy now' in text or 'subscribe this' in text or 'click link' in text:
print("SPAM")
else:
print("OKAY")
Solution 2:[2]
text = input("text : ")
if('make a lot of money' in text) or ('buy now'in text) or ('subscribe this' in text) or ('click link' in text):
print("SPAM")
else:
print("OKAY")
OR
text = input("text : ")
spam_phrases = ['make a lot of money','buy now','subscribe this','click link']
for phrase in spam_phrases:
if phrase in text:
print("SPAM")
break
else:
print("OKAY")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vishwa Mittar |
| Solution 2 |
