记录每次运行得到的变量值

吐槽!CahtGPT写代码的能力越来越差了o(╥﹏╥)o还是只有靠自己啊

首先尝试了logging方法,但是报错python3.8没有encoding变量无法编码非ascii码。使用GPT重写的代码,又无法写入内容到文件里。最后简单粗暴,让GPT给直接写入文件的代码。但是新旧response是否相等的判断一直有问题,最后还是靠自己去看,去debug,才搞完的。前前后后花了两个小时,在此记录。希望下次遇到类似代码,自己能直接写了。

def write_to_file(input, response):
    with open('chatbot.log', 'r', encoding='utf-8') as file:
        lines = file.readlines()  #lines是list类型
    if lines:
        response_old = str(lines[-1]).split(":")[1] #获得“Response:”后的内容
        print("response_old:",response_old.strip()) #response写入时末尾有\n,所以要strip去掉
        print("response:",response)
        print(response_old.strip() in response)
        if response_old.strip() in response:    #判断字符串是否包含用in
            with open('chatbot.log', 'w', encoding='utf-8') as file:
                file.writelines(lines[:-2])  # 删除最后一个input和response的行

    with open('chatbot.log', 'a', encoding='utf-8') as file:
        file.write(f"Input: {input}\n")  #f("{}")指定格式
        file.write(f"Response: {response}\n")

你可能感兴趣的:(python,开发语言)