首页 > 解决方案 > 如何在 python nltk 聊天答案上使用反射

问题描述

NLTKchat.utils模块中,参数之一是“反射”。除了反射的定义,我找不到关于参数的确切解释。或者我找不到聊天响应中显示反射映射的示例。

检查以下示例。如果输入“go”或“hello”,如何输出“gone”或“hey there”?

只是我想知道如何在聊天对答案中注入反射?

from nltk.chat.util import Chat, reflections

my_dummy_reflections= {
    "go"     : "gone",
    "hello"    : "hey there",
    "my": "your",
    "your": "my"
}

pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, How are you today ?",]
    ],
     [
        r"what is your name ?",
        ["my name is Chatty and I'm a chatbot ?",]
    ],
]

chat = Chat(pairs, my_dummy_reflections)
chat.converse()

标签: pythonnltk

解决方案


就像文档已经(模糊地)告诉您的那样,该reflections参数用于映射表达式以反映给正确的人。像这样:

(nltk) tripleee$ python chat.py 
>hello there
None
>my name is my secret
Hello your secret, how are you today?

注意“我的秘密”如何映射到“你的秘密”。这就是reflections照顾。简而言之,返回给用户的字符串已经替换了与反射匹配的任何字符串,因此例如来自用户的第一个参数%1将替换反射关键字。

这是此代码,非常直接地改编自您的尝试。

from nltk.chat.util import Chat, reflections

my_reflections= {
    "you": "I",
    "your": "my",
    "you're": "I'm",
    "I": "you",
    "my": "your",
    "I'm": "you're"
}

pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, how are you today?",]
    ],
     [
        r"what is your name?",
        ["My name is Chatty and I'm a chatbot.",]
    ],
]

chat = Chat(pairs, my_reflections)
chat.converse()

(我冒昧地也删除了标点符号前的错误间距。)

您询问如何完成的任务将通过将输入短语及其响应添加到pairs列表中来轻松实现。


推荐阅读