我有这个基本程序。它需要一个关键字列表,在字符串中查找这些关键字,如果找到关键字,它会根据该匹配执行某些操作。
我总是忘记了从字符串中打印出实际匹配单词所需的步骤。我有一种感觉,我在某个地方错过了一个for循环......
keywords = ["thing1","thing2"]
user_input = "This is a test to see if I can find thing2."
if any(word in user_input for word in keywords):
print "keyword found", word #this gives me a -'word' not defined error"-
else:
print "no"
最简单的方法吗?
谢谢! (对于真正基本的问题感到抱歉,这只是我忘了很多的事情之一。)
答案 0 :(得分:0)
您可以使用for-loop
with an else
clause:
for word in keywords:
if word in user_input:
print "keyword found", word
break
else:
print "no"
另一种方法是使用生成器表达式并next
拉出第一个项目(如果存在):
try:
word = next(word for word in keywords if word in user_input)
print "keyword found", word
except StopIteration:
print "no"
答案 1 :(得分:0)
正则表达式将有所帮助:
import re
words_list = [word for word in keywords if re.search(word, user_input )]
print "These words have been found: %s" % str(words_list)