我正在尝试制作一个响应命令的不和谐的“爸爸机器人”。当有人说“我是”时,它将打印出“嗨,无论他们输入了什么”,我是爸爸机器人,它工作正常,但是很多朋友都输入了“ im”而不是“ I'm”,这意味着我允许很好,但是现在它触发时以单词“ im”结尾,例如他或目标。
这是我尝试过的代码,我也尝试过使用for循环遍历数组。
im = ["aim", "bim", "cim", "dim", "eim", "fim", "gim", "him", "iim", "jim", "kim", "lim", "mim", "nim", "oim", "pim", "qim", "rim", "sim", "tim", "uim", "vim", "wim", "xim", "yim", "zim"]
#part of a larger if statement
elif ("i'm " in message.content.lower() or "im " in message.content.lower()) and not message.content.lower() in im:
if "i'm" in message.content:
you = message.content.split("i'm")
elif "im" in message.content:
you = message.content.split("im")
elif "Im" in message.content:
you = message.content.split("Im")
else:
you = message.content.split("I'm")
await message.channel.send(f"""Hi{you.pop(1)} I'm Dadbot""")
我也尝试过使用这样的for循环
if "im" in message.content:
for x in im:
if im(x) in message.content:
go = 1
break
go = 0
if go == 1:
该代码应仅忽略任何其他文本,并且只应响应“ im”,“ Im”,“ I'm”和“ I'm”
具有如下所示的内容:
User:
"I'm hungry"
Dad bot:
"Hi hungry I'm Dadbot"
这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 251, in _run_event
await coro(*args, **kwargs)
File "C:/Users/User/PycharmProjects/dadBot/dadBot.py", line 26, in on_message
elif ("i'm " in message.content.lower() or "im " in message.content.lower()) and not im in message.content.lower():
TypeError: 'in <string>' requires string as left operand, not list
答案 0 :(得分:1)
我想到了一个像^(im|i\'m)\s+(.*)
这样的小正则表达式
示例:
import re
ip = "im hungrey"
list_ip = re.match(r"^(im|i\'m)\s+(.*)",ip, re.IGNORECASE)
if list_ip:
print('Hi '+ list_ip.group(2) + ' '+list_ip.group(1)+ ' Dadbot')
输出:
i/p: "im hungrey"
o/p: Hi hungrey im Dadbot
i/p: "him hi"
o/p: null
i/p: "i'm all"
o/p: Hi all i'm Dadbot
说明:
re
-python中的正则表达式进行模式匹配group(1)
是(im|i\'m)
-它给了我第一个单词group(2)
是(.*)
-它提供了输入的剩余部分答案 1 :(得分:0)
对我来说很好。我修改了代码以在本地执行。看来问题出在message.content
中。我猜它输出的是列表,而不是字符串。
sample = "I'm hungry"
im = ["aim", "bim", "cim", "dim", "eim", "fim", "gim", "him", "iim", "jim", "kim", "lim", "mim", "nim", "oim", "pim", "qim", "rim", "sim", "tim", "uim", "vim", "wim", "xim", "yim", "zim"]
#part of a larger if statement
if ("i'm " in sample.lower() or "im " in sample.lower()) and not sample.lower() in im:
if "i'm" in sample:
you = sample.split("i'm")
elif "im" in sample:
you = sample.split("im")
elif "Im" in sample:
you = sample.split("Im")
else:
you = sample.split("I'm")
print(f"""Hi{you.pop(1)} I'm Dadbot""")
答案 2 :(得分:0)
m="Im hungry"
d=m.lower().replace("'","").split(' ')
if "im" in d:
z=d[d.index("im")+1]
print "hey " + z +" how are you?"
如果您尝试的是捕获名称,则此方法也可能有效。