Skip to main content
 首页 » 编程设计

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

2024年09月07日24insus

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

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

此代码仅输出“这首歌不含任何脏话。”

请您参考如下方法:

我推荐几个想法:

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