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

时间:2018-06-05 16:40:41

标签: python input filter profanity

我希望用户输入歌词到该程序(稍后将扩展到搜索网站,但我目前不需要帮助),程序将告诉我输入的信息是否包含列表中的单词。

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")

此代码只输出'这首歌是亵渎性的。'

1 个答案:

答案 0 :(得分:2)

我建议有几个想法:

  • 使用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)