如何为关系添加第二个数组,以便聊天机器人从第二个数组询问关系?

2024-03-28 23:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在聊天机器人中添加一个新主题,向用户提问。比如:如果我说“我感觉很快乐”,聊天机器人会问“你为什么快乐”,下一个答案来自用户:“因为我哥哥给了我一个机会。”聊天机器人会问“你哥哥叫什么名字?”

我试图添加一个新数组作为关系,但没有成功

import random

class simplechatbot:

    def run(self):

        welcome = "Hi, what you want to talk about?"
        goodbye = "goodbye"
        feelings = ["afraid", "sick", "stressed", "happy", "unhappy"]
#         relation = ["father", "mother", "sister", "brother"]   # I want to add this also to interact 
        dummy_sentences = [
            "say something about it",
            "Interesting",
            "I didn't get it, could you please explain",
            "what do you think about it?"
        ]

        # Greet the user
        print(welcome);


        # Process user input. Processing continues until the user says goodbye. 
        s = ""
        while s != goodbye:
            # Read user input
            s = input()
#             s = s.lower()

            if s == goodbye:
                print(goodbye);
                break
            answer = ""
            # Check for feelings
            for feeling in feelings:
#                 for relation in relation:
                if feeling in s:
                    # Found feeling -> generate answer
                    answer = "Why you are feeling " + feeling + "?"
                        # stop processing user input
                    break;
#                     elif relation in s:
#                         answer = "what's the name of your", relation, "?"
#                         # stop processing user input
#                         break;

            # If no feeling has been detected, generate a dummy answer.
            if len(answer) == 0:
                # output random sentence
                answer = random.choice(dummy_sentences)

            print(answer)

mychatbot = simplechatbot()
mychatbot.run()

我的实际结果是:

Hi, what you want to talk about?
Hi
say something about it
I'm sick 
Why you are feeling sick?

我想说一些关于我父亲的事,这里聊天机器人应该问问我父亲 说说看


Tags: toanswerinyouinput机器人itrandom
1条回答
网友
1楼 · 发布于 2024-03-28 23:22:25

有一个高级问题阻碍了您的功能。调试尝试很快就会发现这一点。查看这个可爱的debug博客寻求帮助

特别要注意以下几行

    relation = ["father", "mother", "sister", "brother"]
    ...
        for feeling in feelings:
          for relation in relation:

此时,您已经删除了关系列表:变量relation现在只引用字符串“父”。下次在feelings循环的第二次迭代中使用此语句时,将遍历father的字符,分配relation = 'f'并丢失其余字符

我建议您像对待feelings一样对待关系列表:

    relations = ["father", "mother", "sister", "brother"]
    ...
        for feeling in feelings:
          for relation in relations:

现在我们可以取得一些进展。对话范例:

Hi, what you want to talk about?
I'm sick
Why you are feeling sick?
My father has the flu, and I think I might catch it.
("what's the name of your", 'father', '?')

最后一个“句子”具有不同的格式,因为您将片段指定为元组,而不是将它们串联起来。你能从这里拿走吗

相关问题 更多 >