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

时间:2019-05-03 17:35:08

标签: python chatbot

我想在聊天机器人中添加一个新主题以询问用户。诸如此类:如果我说“我感到很高兴”,那么聊天机器人将询问“为什么要感到高兴”,下一个答案将来自用户:“因为我的兄弟给了我一个机会。”然后聊天机器人会询问“您的兄弟名字是什么””

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

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?

我想谈谈我父亲的事######在这里聊天机器人应该问我父亲的事     说些什么

1 个答案:

答案 0 :(得分:0)

有一个高级问题阻止了您的功能。调试尝试会很快发现这一点。请访问这个可爱的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', '?')

最后一个“句子”具有不同的格式,因为您将片段分配为元组,而不是将它们连接在一起。你可以从这里拿走吗?