You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python NLTK Chat模块中使用reflections实现应答映射

NLTK Chat模块reflections参数使用说明

1. reflections参数的作用

你传入Chat类的自定义映射字典已经成功注入到实例中,reflections的默认逻辑是对正则匹配到的分组内容进行自动词汇替换,不会直接作为全输入匹配规则使用。
举个验证示例,你可以在原有pairs中新增一条测试规则:

[
    r"you said (.*)",
    ["I heard you said: %1",]
]

当你输入you said my go to hello时,正则匹配到的分组内容是my go to hello,会自动经过my_dummy_reflections做替换,最终输出结果为I heard you said: your gone to hey there,可以看到映射规则已经生效。

2. 实现输入go/hello返回对应映射内容的方案

你需要的全输入匹配触发对应输出的效果,有两种实现方式:

方案1:直接写配对规则(适合映射条目少的场景)

直接在pairs中新增对应匹配规则即可:

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 ?",]
    ],
    # 新增匹配规则
    [
        r"^hello$",
        ["hey there",]
    ],
    [
        r"^go$",
        ["gone",]
    ]
]

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

方案2:结合reflections动态匹配(适合映射条目多的场景)

新增一条通用匹配规则,利用reflections的自动替换能力动态返回映射结果,不需要逐个写应答内容:

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 ?",]
    ],
    # 新增通用单字匹配规则
    [
        r"^(\w+)$",
        ["%1",]
    ]
]

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

该方案下,你输入hello时匹配到的分组内容为hello,经过reflections替换后就会自动输出hey there,输入go自动输出gone,同时原有反射替换逻辑不受影响。

内容的提问来源于stack exchange,提问作者sugunan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:54:03