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

Python开发Eliza精神续作:提取用户输入生成个性化回复

实现思路与代码示例

要实现提取用户输入关键词外的内容并整合到回复中,核心是模式匹配+内容捕获+模板替换,用Python基础语法(内置re和random模块)就能完成,以下是具体方案:

1. 修正现有代码的小问题

你当前代码里的input(random.choice(...))是错误的——这会让程序等待用户输入问候语,而不是电脑主动输出问候。应该改成print():

if feeling == "Negative":
    print(random.choice(negativeGreetings))
elif feeling == "Neutral":
    print(random.choice(neutralGreetings))
elif feeling == "Positive":
    print(random.choice(positiveGreetings))

2. 核心实现逻辑

步骤1:定义模式与回复模板

用正则表达式匹配用户输入的句式,通过捕获组提取需要的内容,同时为每个模式准备多个回复模板(避免重复生硬):

import re
import random

# 模式-回复模板映射:正则捕获组对应模板中的占位符{0}, {1}...
response_patterns = [
    # 匹配"我[时间/修饰]得去[动作]"类输入
    (
        r"我(.*)得去(.*)",
        [
            "你是必须去{1},还是只是觉得应该去?",
            "{0}必须去{1}吗?能说说原因吗?"
        ]
    ),
    # 匹配"我觉得[内容]"类输入
    (
        r"我觉得(.*)",
        [
            "你为什么会有这样的感觉?",
            "能详细说说你觉得{0}的原因吗?"
        ]
    ),
    # 匹配"我[动作]了[对象]"类输入
    (
        r"我(.*)了(.*)",
        [
            "{0}了{1}之后,你有什么感受?",
            "能说说你{0}{1}的细节吗?"
        ]
    ),
    # 通用兜底回复(无匹配时触发)
    (
        r".*",
        [
            "能再详细说说吗?",
            "我不太明白你的意思,可以解释一下吗?"
        ]
    )
]

步骤2:实现人称转换

参考Eliza的经典特性:把用户输入的第一人称(我、我的)转换成第二人称(你、你的),让回复更符合对话逻辑:

def transform_person(text):
    """转换文本中的人称指代"""
    replacements = {
        "我": "你",
        "我的": "你的",
        "我自己": "你自己",
        "我们": "你们"
    }
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text

步骤3:生成回复的核心函数

遍历所有模式,找到匹配项后提取捕获内容、转换人称,再随机选择模板填充内容:

def generate_response(user_input):
    user_input = user_input.strip()
    for pattern, templates in response_patterns:
        match = re.match(pattern, user_input)
        if match:
            # 对捕获的内容进行人称转换
            captured_content = [transform_person(group) for group in match.groups()]
            # 随机选一个模板并填充内容
            return random.choice(templates).format(*captured_content)
    # 兜底回复
    return random.choice(["能再详细说说吗?", "我不太明白你的意思。"])

3. 整合到聊天循环

把上述逻辑和你现有的情绪问候结合,形成完整的聊天流程:

# 你原有的问候语列表(自行填充更多内容)
negativeGreetings = ["你看起来有点低落,能说说怎么了吗?"]
neutralGreetings = ["今天想聊点什么?"]
positiveGreetings = ["看起来你心情不错,分享一下吧!"]

def chat():
    # 假设这里已通过逻辑确定用户情绪(示例用Neutral)
    feeling = "Neutral"
    
    # 输出初始问候
    if feeling == "Negative":
        print(random.choice(negativeGreetings))
    elif feeling == "Neutral":
        print(random.choice(neutralGreetings))
    elif feeling == "Positive":
        print(random.choice(positiveGreetings))
    
    # 对话循环
    while True:
        user_input = input("> ").strip()
        # 退出条件
        if user_input.lower() in ["退出", "再见", "拜拜"]:
            print("再见!")
            break
        # 生成并输出回复
        print(generate_response(user_input))

if __name__ == "__main__":
    chat()

测试示例

用户输入:我今天得去健身
程序输出(随机):你是必须去健身,还是只是觉得应该去?

用户输入:我觉得我的工作很无聊
程序输出(随机):能详细说说你觉得你的工作很无聊吗?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 04:39:49