[英]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")
That' because you're comparing with equals
:那是因为你正在与
equals
进行比较:
text == 'make a lot of money' in text
instead just use the in
command:而只是使用
in
命令:
'make a lot of money' in text
will yield True
if the text contains that string如果文本包含该字符串,将产生
True
You're not using correct syntax for if statement, please use this:您没有为 if 语句使用正确的语法,请使用:
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")
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.