Python-如果字符串包含列表中的单词或

2024-04-28 05:14:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经找得很彻底,没有找到合适的答案。我对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!")

使用上述方法,如果用户将整个字符串中的一个确切的单词输入整串,它将打印“退出诅咒”;但是,如果用户输入“诅咒”或“我喜欢说诅咒”,它会打印“听起来太好了!”

最终,我需要的是能够搜索整个字符串中的关键字,而不是整个字符串的完全匹配。例如:“我去了公园,觉得尖叫的诅咒应该会在比赛中变成现实。


Tags: 字符串答案用户typingnot关键字建议例子
3条回答
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.
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.

你可以使用集合,如果你想检查脏话的存在

a_swear_set = set(Swear)

if a_swear_set & set(Userinput.split()):
     print("Quit Cursing!")
else:
     print("That sounds great!")

相关问题 更多 >