如何检查字符串是否包含lis中的单词

2024-06-06 11:09:40 发布

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

我希望用户输入歌词的程序(这将扩展到搜索一个网站,但我目前不需要这方面的帮助)和程序将告诉我,如果输入的信息包含一个词从一个列表。在

banned_words = ["a","e","i","o","u"] #This will be filled with swear words

profanity = False

lyrics = input ("Paste in the lyrics: ")
for word in lyrics:
    if word in banned_words:
        print("This song says the word "+word)
        profanity = True

if profanity == False:
    print("This song is profanity free")

这段代码只是输出“这首歌没有亵渎”


Tags: the用户in程序falseifsong歌词
1条回答
网友
1楼 · 发布于 2024-06-06 11:09:40

我有几个建议:

  • 使用str.split按空格拆分。在
  • 使用set进行O(1)查找。这由{}表示,而不是用于列表的[]。在
  • 在函数中包装逻辑。这样一来,只要一听到脏话,你就可以简单地return。这样就不再需要else语句。在
  • 使用函数意味着您不需要设置默认变量,然后在适用的情况下重新赋值。在
  • 使用str.casefold捕获大小写单词。在

下面是一个例子:

banned_words = {"a","e","i","o","u"}

lyrics = input("Paste in the lyrics: ")

def checker(lyrics):
    for word in lyrics.casefold().split():
        if word in banned_words:
            print("This song says the word "+word)
            return True
    print("This song is profanity free")
    return False

res = checker(lyrics)

相关问题 更多 >