在字符串中查找特定单词 Python

Find a specific word in a string Python

我正在制作一个对某些词做出反应的 Discord 机器人,问题是我的机器人对一组匹配的字符而不是词本身做出反应。

例如:

words = ["example1", "example2"]
for x in words:
    if x in message.content.lower():
         message.channel.send("yes")

我的预期反应:
第一条消息:example1 机器人:“是”
第二条消息:aaaexample1aaa bot:应该什么都不做,但实际上 bot 响应:“是”
第三条消息:example1aaa bot:应该什么都不做,但实际上 bot 响应:“是”

你在看你的话两边的空白吗?

如...

words = [" example1 ", " example2 "] 
for x in words: if x in message.content.lower(): 
    message.channel.send("yes")

?

但是,看起来您还需要进行前导字符串检查,所以

words = ["example1", "example2"] 

msg = message.content.lower().translate({ord(i):None for i in ',.;'})  #Removing punctuation that would screw up line split - may or may not want to do that, in which case remove the .translate()
for word in words:    
    if word.center(len(word)+2) in msg \
    or msg[:len(word)+1] == word.ljust(len(word)+1) in msg:
        message.channel.send("yes")

尝试将字符串转换为数组,然后使用 in 关键字

缓存数组比一直调用它要快

words = ["example1", "example2"]
message_array = message.content.lower().split(' ')
for x in words:
    if x in message_array:
         message.channel.send("yes")

直接使用正则表达式会更好。 (import re)

在您的代码中,您可以将 if x in message.content.lower() 更改为 if x == message.content.lower() 以匹配确切的词。