2

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

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

此代码仅输出“这首歌无亵渎”。

4

1 回答 1

2

我推荐几个想法:

  • 使用str.split.
  • 用于setO(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)
于 2018-06-05T16:47:38.750 回答