python - 有没有办法让 Discord Dadbot 稍后在消息中找到“我是”?
问题描述
所以我正在我的 Discord 服务器上使用 Python 开发一个个人机器人,它可以做很多事情,其中之一是模仿常见的 Dadbot。这是执行此操作的代码:
if any(word in msg for word in imlist):
resp = message.content.split(" ",1)[1]
await message.channel.send("Hi "+ resp +", I'm Pigeonbot")
if any(word in msg for word in iamlist):
resp = message.content.split(" ",2)[2]
await message.channel.send("Hi "+ resp +", I'm Pigeonbot")
这是两个列表:
imlist = ["I'm", "Im", "im", "i'm", "IM", "I'M"]
iamlist = ["i am", "I am", "I AM"]
如果您输入不和谐的消息,例如“我饿了”,它会回复“嗨,饿了,我是 Pigeonbot”。但是,如果你在“我是”之前说一些东西,例如“外面很热,我很饿”,它会返回“你好,外面很热,我很饿,我是 Pigeonbot”。有没有办法让机器人在消息中找到 imlist 或 iamlist 的位置并从那里启动“嗨 [],我是 Pigeonbot”?谢谢 :)
解决方案
您可以使用正则表达式I(?:'| a)?m ([^\s]*)
演示
解释:
I
: 匹配文字I
。(?:...)?
:使内容成为可选的非捕获组。'| a
: 非捕获组的内容:匹配撇号,或空格和a
。m
: 匹配一个m
然后是一个空格。(...)
:创建捕获组[^\s]*
: 匹配除空格以外的任意字符,任意次数
从演示中可以看出,这只会捕获I'm
. 如果您想在之后捕获所有内容I'm
,可以将正则表达式更改为I(?:'| a)m (.*)
Demo。在这里,捕获组的内容匹配任意字符,任意次数。
import re
expr1 = re.compile(r"I(?:'| a)m ([^\s]*)", re.IGNORECASE) # Use the re.IGNORECASE flag for case-insensitive match
expr2 = re.compile(r"I(?:'| a)m (.*)", re.IGNORECASE)
test_texts = ["I'm hungry", "It's hot and I'm parched", "I'm not stupid", "I'm going to go to bed now, see you tomorrow"]
for s in test_texts:
print(f"text: {s}")
match = re.search(expr1, s)
if match:
resp = match.group(1)
print(f"\texpr1: Hi {resp}, I'm pigeonbot")
match2 = re.search(expr2, s)
if match2:
resp2 = match2.group(1)
print(f"\texpr2: Hi {resp2}, I'm pigeonbot")
这给了我们输出:
text: I'm hungry
expr1: Hi hungry, I'm pigeonbot
expr2: Hi hungry, I'm pigeonbot
text: It's hot and I'm parched
expr1: Hi parched, I'm pigeonbot
expr2: Hi parched, I'm pigeonbot
text: I'm not stupid
expr1: Hi not, I'm pigeonbot
expr2: Hi not stupid, I'm pigeonbot
text: I'm going to go to bed now, see you tomorrow
expr1: Hi going, I'm pigeonbot
expr2: Hi going to go to bed now, see you tomorrow, I'm pigeonbot
推荐阅读
- qt - 为什么我的嵌套 ListViews 只显示外部模型的一个元素?
- database - SQLAlchemy 从表中不存在的列表中查找 ID
- php - 对 XPath 查询使用 XSD 模式验证
- java - 为什么我不能取消我的执行人提交的工作?
- ssis - 我可以只执行已部署 SQL 目录中包中的某些任务吗?
- excel - 遍历所有工作表以查找包含特殊字符的单元格
- python-3.x - 如何在使用 abs 后添加 str 文本(+ 的不支持的操作数类型:'float' 和 'str')
- php - 一些限制后不可能卷曲欺骗网址
- excel - 如何将我的 excel 工作表值传递给我的 sql 查询
- chatbot - 无法为 watson 连接器运行 botium