因此,在我正在开发的GroupMe机器人中,我让机器人通过在webhooks中传递消息来响应。
def webhook():
# 'message' is an object that represents a single GroupMe message.
message = request.get_json()
speaker = message['name']
# If hypefact! is spoken, return random fact
# This code replies once and then calls another function that replies again
if 'hypefact!' in message['text'].lower() and not sender_is_bot(message):
reply(speaker + ' - Here is your Hype Fact: ')
reply(fact_delivery())下面是get_weather的函数
def get_weather(city):
## Bunch of stuff happens
reply(weatherData['currently']['summary'] + ', ' + str(
weatherData['currently']['apparentTemperature']) + degree_sign + 'F. ' + weatherData['hourly'][
'summary'] + '\n\n' + weatherData['daily']['summary'])如果一个短语是"in message‘’text‘“,它将触发一个动作,因为它在消息中。
如果我想让它解析这条信息。
“这个周末奥斯汀的天气怎么样?”
这句话的关键部分是“奥斯汀的天气”。
所以我想把"in“后面的单词解析为get_weather(城市)
预期工作流程:聊天人员在message触发器中用“天气在{ city }”表示短语,从字符串中筛选出城市以调用get_weather函数
发布于 2018-05-02 20:54:02
您可以使用正则表达式,但这并不明显。你描述的这个案子很容易被抓住。
import re
text = "Whats the weather in Austin this weekend"
match = re.search('[Ww]eather in (?P<city>\w+)', text)
if match:
print(match.groupdict()) # {'city': 'Austin'}
else:
pass # the text does not contain "weather in {CITY}" pattern但并不是所有的城市都有一个词的名字。所以,诀窍是告诉城市的名字何时结束和“其余的句子”开始。例如,您可以依赖以大写字母开头的所有单词都是城市名称的一部分。
text2 = "Whats the weather in New York this weekend"
match2 = re.search('[Ww]eather in (?P<city>([A-Z]\w+\W+)+)', text2)
if match2:
print(match2.groupdict()) # {'city': 'New York '}
else:
pass # the text does not contain "weather in {CITY}" pattern但是当你想创造一个聊天机器人的时候,有多少人会在聊天中使用大写字母和标点符号呢?
因此,您可能需要在捕获到的城市名称之后,与一些预定义的城市名称列表(我认为不应该太大)对齐。
https://stackoverflow.com/questions/50143155
复制相似问题