首页 > 解决方案 > 如何在我的字典中搜索关键词和短语以执行功能

问题描述

为了通过做项目进行一点学习,我正在尝试构建一个简单的人工智能,它可以响应关键字(例如“日期”)和短语(例如“明天的天气”)并具有适当的功能。它适用于简单的关键字,但似乎找不到一个短语。

我已经尝试 .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]())

我试图让程序在一个完整的句子中注册一个关键短语(例如“明天天气”)(例如“嘿,明天的天气怎么样?”并且如果可能的话,比较关键字和短语并给予短语优先级,因为合适的短语比一个关键字更准确。

这是我第一次在这里发帖,所以我为我犯的任何错误道歉!我愿意接受任何形式的批评!提前致谢!

标签: pythondictionary

解决方案


我在您当前的代码中添加了一些打印语句来说明问题:

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: 

我希望这能让你走上解决方案的正确轨道。


推荐阅读