python - 如何在我的字典中搜索关键词和短语以执行功能
问题描述
为了通过做项目进行一点学习,我正在尝试构建一个简单的人工智能,它可以响应关键字(例如“日期”)和短语(例如“明天的天气”)并具有适当的功能。它适用于简单的关键字,但似乎找不到一个短语。
我已经尝试 .strip 命令,但它没有找到任何东西。
from basics_jarvis import *
jarvis_functions = {
"date": lambda: todays_date(), #These are functions from a different .py
"datum": lambda: todays_date(),
"weather": lambda: weather_today(),
"weather tomorrow": lambda: weather_tomorrow(),
"tomorrows weather": lambda: weather_tomorrow(),
"What do you think?": lambda: print("Im not an AI, I dont think")
}
Loop = True
while Loop:
command = input("Awaiting orders \n")
for keyword in command.split(): #.strip just breaks the code
if keyword in jarvis_functions:
print(jarvis_functions[keyword]())
我试图让程序在一个完整的句子中注册一个关键短语(例如“明天天气”)(例如“嘿,明天的天气怎么样?”并且如果可能的话,比较关键字和短语并给予短语优先级,因为合适的短语比一个关键字更准确。
这是我第一次在这里发帖,所以我为我犯的任何错误道歉!我愿意接受任何形式的批评!提前致谢!
解决方案
我在您当前的代码中添加了一些打印语句来说明问题:
while True:
command = input("\nAwaiting orders: ")
print('received command:', repr(command))
for keyword in command.split():
print(' keyword', repr(keyword))
if keyword in jarvis_functions:
print(jarvis_functions[keyword]())
结果输出为:
Awaiting orders: hey, whats tomorrows weather
received command: 'hey, whats tomorrows weather'
keyword 'hey,'
keyword 'whats'
keyword 'tomorrows'
keyword 'weather'
Awaiting orders:
如您所见,该命令被拆散并且tomorrows
不再weather
在一起。
相反,我建议遍历关键字并查看它们是否出现在命令中。也许是这样的:
jarvis_functions = {
"tomorrows weather": lambda: print('1'),
"What do you think?": lambda: print("Im not an AI, I dont think"),
}
while True:
command = input("\nAwaiting orders: ")
print('received command:', repr(command))
for keyword, func in jarvis_functions.items():
print(' keyword', repr(keyword))
if keyword in command:
print(' keyword was found')
func()
# no need to check other keywords
break
输出将是:
Awaiting orders: hey, whats tomorrows weather
received command: 'hey, whats tomorrows weather'
keyword 'tomorrows weather'
keyword was found
1
Awaiting orders: something new
received command: 'something new'
keyword 'tomorrows weather'
keyword 'What do you think?'
Awaiting orders:
我希望这能让你走上解决方案的正确轨道。
推荐阅读
- keycloak - 更改 Keycloak 注销重定向 url
- node.js - 如何使用用户 ID 查找喜欢的帖子
- c# - .Net 5 中的 ManualResetEvent
- python - IndexError:元组索引超出范围(np.shape,reshape)
- intellij-idea - 为什么在使用带有 FX 的 OpenJDK 的 Azul Zulu 构建将 JavaFX 项目升级到 JDK 17 后,IDEA 找不到 JavaFX 包?
- r - 简单但不容易的合并任务
- flutter - Flutter 三元条件为 null 而不是 bool 的子类型
- mysql - 如何从 mySQL 数据库中只获取一个对象?
- c# - 使用特定格式格式化日期
- xaml - VS2019 或 VS2022 中的 WinUI 项目没有 XAML 热重载