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

Python基于random模块开发AI程序时append功能异常问题排查

Python学习型聊天机器人bug修复

问题背景

使用Python开发具备未知输入学习能力的AI聊天程序,引入random模块实现随机问候/告别,调用列表append()方法实现新关键词和对应回复的动态新增,初始实现代码如下:

import random
greetings=["Hi there!","Sup!"]
goodbye=["have a nice day","byee!"]
keywords=["maths","swimming"]
responses=["one of the most interesting subjects","The best sport in the world"]
print(random.choice(greetings))
user=input("Chat with me(type 'bye' to quit) -> ")
user=user.lower()
keyword_found=False
while(user!="bye"):
    
    for i in range(len(keywords)):
        if(keywords[i] in user):
            print("Bot: "+responses[i])
            keyword_found==True
    if(keyword_found==False):
        new_keyword=input("Couldn't get ya. pls tell me the name of the topic which you are talking about : ")
        keywords.append(new_keyword)
        new_response=input("Pls tell me about it : ")
        responses.append(new_response)
    user=input("Chat with me(type 'bye' to quit) -> ")
    user=user.lower()

程序存在的异常:初始预设的关键词可以正常触发对应回复,但是通过append()动态新增关键词和回复后,后续再输入相关内容依然会弹出"Couldn't get ya"的未识别提示,无法触发已经学习过的回复。

根因定位

代码存在3处逻辑错误:

  • 标记位赋值写错:匹配到关键词时写的是keyword_found==True,这是相等判断表达式,不会给变量重新赋值,keyword_found从初始化后永远是False,不管有没有匹配到关键词都会触发未识别的学习流程。
  • 标记位没有按轮次重置:就算修复赋值问题,keyword_found一旦在某一轮被设为True,后续所有轮次都会保持这个值,不会再触发新内容学习逻辑。
  • 大小写逻辑不统一:用户输入会统一转成小写处理,但新增学习的关键词没有做小写转换,会出现大小写不一致导致的匹配失败。
    另外初始定义的goodbye告别语列表没有被调用,属于冗余代码。

修复后完整代码

import random
greetings = ["Hi there!", "Sup!"]
goodbye = ["have a nice day", "byee!"]
keywords = ["maths", "swimming"]
responses = ["one of the most interesting subjects", "The best sport in the world"]
print(random.choice(greetings))
user = input("Chat with me(type 'bye' to quit) -> ")
user = user.lower()

while user != "bye":
    # 每轮对话开始前重置匹配标记
    keyword_found = False
    for i in range(len(keywords)):
        if keywords[i] in user:
            print("Bot: " + responses[i])
            # 修正:将相等判断==改为赋值=
            keyword_found = True
    if not keyword_found:
        new_keyword = input("Couldn't get ya. pls tell me the name of the topic which you are talking about : ")
        # 新增关键词统一转小写,和输入预处理逻辑对齐
        keywords.append(new_keyword.lower())
        new_response = input("Pls tell me about it : ")
        responses.append(new_response)
    user = input("Chat with me(type 'bye' to quit) -> ")
    user = user.lower()

# 退出时输出随机告别语
print(random.choice(goodbye))

修复点说明

  • 将关键词匹配分支的keyword_found==True修改为keyword_found = True,正确更新匹配标记位的状态
  • 每次进入循环处理新的用户输入时,先把keyword_found重置为False,避免上一轮的匹配状态干扰本轮判断
  • 新增学习的关键词统一调用.lower()转成小写,和用户输入的预处理规则保持一致,避免大小写差异导致的匹配失效
  • 补上告别语逻辑,用户输入bye退出时随机从goodbye列表选取内容输出,复用初始定义的列表数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:39:29