在Python中匹配字符串中的多个关键字

发布于 2025-01-12 07:07:38 字数 982 浏览 0 评论 0原文

正在做一些探索性的Python,请对我温柔点:)

我正在尝试解析我在Python中收到的消息。我想要做的是:如果我在消息中查找的 1-n 个关键字列表匹配,则执行一个函数(例如发回消息)。

例如,假设传入的消息是“黄色巴士在蓝天下的绿草上行驶”:下面的代码应该能够解释“黄色”、“绿色”和“蓝色”,无论我实际的顺序如何已在下面列出,并执行操作。


#this doesn't work, I'm missing something with integrating a list lookup somewhere?
@app.message("green","blue","yellow")
def say_hello(message, say):
    user = message['user']
    say(f"Winner")

#this doesn't work as it only see's "Green" first and accepts it as correct. If the message was "The green and yellow car", that shouldn't be accepted as correct, as blue is not listed
@app.message(re.compile("(green|blue|yellow)"))
def say_hello_regex(say, context):
    greeting = context['matches'][0]
    say(f"Hi")

我花了很多时间使用 re.compile 查看示例操作系统,以及有趣的前向/后向 RE 示例、管道(OR)等,但没有一个达到我想要的效果。我认为 RE 不是我的答案...我确实看到人们推荐关键字列表,但不确定我应该如何嵌入到代码中。

Doing some exploratory Python, be gentle with me :)

I'm trying to parse a message I'm receiving in Python. What I want to do is: if the 1-n list of keywords I'm looking for in the message match, perform a function (send a message back, as an example).

For example, let's say the incoming message is "The yellow bus drove on green grass under the blue sky": My code below should be able to interpret "yellow","green", and "blue", regardless of the order I actually have listed below, and perform the action.


#this doesn't work, I'm missing something with integrating a list lookup somewhere?
@app.message("green","blue","yellow")
def say_hello(message, say):
    user = message['user']
    say(f"Winner")

#this doesn't work as it only see's "Green" first and accepts it as correct. If the message was "The green and yellow car", that shouldn't be accepted as correct, as blue is not listed
@app.message(re.compile("(green|blue|yellow)"))
def say_hello_regex(say, context):
    greeting = context['matches'][0]
    say(f"Hi")

I spent a lot of time on SO looking through examples os using re.compile, with fun forward/back looking RE examples, piping (OR), etc, but none of them get to what I'm after. I'm thinking RE isn't my answer...I do see people recommending keyword lists, but unsure how I'm supposed to embed into the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文