我怎样才能使 2 个输入具有相同的输出?

问题描述 投票:0回答:2

嗨,我是 python 的新手,我想知道是否有可能对两个不同的输入有相同的响应?

import re

# Define a list of keywords and their associated responses.
keywords_to_responses = {
    'hello' and 'hi': 'Hi there! How can I help you?',
    'goodbye': 'Goodbye!',
    'thank you': 'You\'re welcome! Let me know if you need any more help.',
    'how are you': 'I\'m just a chatbot, but I\'m here to help! How can I assist you today?',
}

def find_matching_response(user_input):
    for keyword, response in keywords_to_responses.items():
        if re.search(r'\b' + keyword + r'\b', user_input):
            return response
    return 'I\'m sorry, I don\'t understand. Can you please rephrase your question?'

def main():
    print('Welcome to the Chatbot! (Type "quit" to exit)')

    while True:
        user_input = input('You: ').lower()

        if user_input == 'quit':
            break

        response = find_matching_response(user_input)
        print('Chatbot:', response)

if __name__ == '__main__':
    main()

我原以为它对 hello 和 hi 给出相同的响应,但它只给出了 hi 的响应。我该如何更改?

python function input output
2个回答
2
投票

在您当前的方法中,您在字典键中使用

and
运算符,由于
'hello' and 'hi'
是布尔运算,因此无法按预期工作。它将返回“hi”,因为在 Python 中,如果所有值都为真,
and
运算符将返回最后一个值。

相反,为了实现所需的行为,您可以通过为字典中的每个关键字定义单独的条目来将多个键映射到相同的值,如下所示:

keywords_to_responses = {
    'hello': 'Hi there! How can I help you?',
    'hi': 'Hi there! How can I help you?',
    'goodbye': 'Goodbye!',
    'thank you': 'You\'re welcome! Let me know if you need any more help.',
    'how are you': 'I\'m just a chatbot, but I\'m here to help! How can I assist you today?',
}

现在,'hello' 和 'hi' 都会给出相同的响应。


1
投票

为 hello 和 hi 添加一个单独的条目。这样,两个词(字典中的键)将映射到同一个句子(字典中的值)。

# Define a list of keywords and their associated responses.
keywords_to_responses = {
    'hello': 'Hi there! How can I help you?',
    'hi': 'Hi there! How can I help you?',
    'goodbye': 'Goodbye!',
    'thank you': 'You\'re welcome! Let me know if you need any more help.',
    'how are you': 'I\'m just a chatbot, but I\'m here to help! How can I assist you today?',
}
© www.soinside.com 2019 - 2024. All rights reserved.