我搜索得非常彻底,但没有找到合适的答案。我是Python / Programming的新手,所以我很感激我能得到的任何建议:
我正在尝试搜索某些关键字的用户输入字符串。例如,我们会说过滤亵渎。根据我的研究,我已经能够制作以下虚拟示例:
Swear = ("curse", "curse", "curse") #Obviously not typing actual swear words, created a set
Userinput = str.lower(input("Tell me about your day: "))
if Userinput in Swear:
print("Quit Cursing!")
else:
print("That sounds great!")
使用上述内容,如果用户输入一个确切的单词形式作为整个字符串,它将打印“quit cursing”;但是,如果用户输入“诅咒”或“我喜欢说诅咒”,它将打印“听起来很棒!”
最终我需要的是能够在整个字符串中搜索关键字,而不是整个字符串的完全匹配。例如:“我去了公园,感觉像尖叫诅咒 s”应该返回真实的比赛。
答案 0 :(得分:6)
Swear = ["curse", "curse", "curse"]
for i in Swear:
if i in Userinput:
print 'Quit Cursing!'
You should read up on the differences between lists and tuples.
答案 1 :(得分:1)
Swear = ("curse", "curse", "curse")
Userinput = str.lower(raw_input("Tell me about your day: "))
if any(Userinput.find(s)>=0 for s in Swear):
print("Quit Cursing!")
else:
print("That sounds great!")
Tell me about your day: curse
Quit Cursing!
Tell me about your day: cursing
That sounds great!
Tell me about your day: curses
Quit Cursing!
Tell me about your day: I like curse
Quit Cursing!
使用正则表达式:
使用的模式是r"\bcurse[\w]*"
。
Swear = ("curse", "curse", "curse")
Userinput = str.lower(raw_input("Tell me about your day: "))
if any(match.group() for match in re.finditer(r"\bcurse[\w]*", Userinput)) :
print("Quit Cursing!")
else:
print("That sounds great!")
finditer(pattern, string, flags=0)
Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a match object.
Empty matches are included in the result.
答案 2 :(得分:1)
你可以使用集合,只要你想检查咒骂词的存在,
a_swear_set = set(Swear)
if a_swear_set & set(Userinput.split()):
print("Quit Cursing!")
else:
print("That sounds great!")