Python - If string contains a word from a list or set
我查得很彻底,没有找到合适的答案。我对python/programming是个新手,因此我很欣赏我能得到的任何建议:
我正在尝试搜索用户输入字符串中的某些关键字。例如,我们将说过滤掉亵渎。从我的研究中,我已经能够做出以下虚拟的例子:
1 2 3 4 5 6 7 | 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!") |
使用上面的方法,如果用户从集合中输入一个确切的单词作为整个字符串,它将打印"退出诅咒";但是,如果用户输入"诅咒"或"我喜欢说诅咒",它将打印"听起来很棒!"
最终,我需要的是能够搜索整个字符串中的关键字,而不是整个字符串的精确匹配。例:"我去了公园,感觉像是在尖叫诅咒",应该回到真实的比赛。
1 2 3 4 5 | Swear = ["curse","curse","curse"] for i in Swear: if i in Userinput: print 'Quit Cursing!' |
你应该读一下列表和元组之间的区别。
你可以使用集合,如果你只想检查脏话的存在,
1 2 3 4 5 6 | a_swear_set = set(Swear) if a_swear_set & set(Userinput.split()): print("Quit Cursing!") else: print("That sounds great!") |
。
1 2 3 4 5 6 7 | 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!") |
号结果:
1 2 3 4 5 6 7 8 9 10 11 | 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! |
使用正则表达式:
使用的模式是
1 2 3 4 5 6 7 | 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!") |
。
1 2 3 4 5 | 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. |