开发者社区 问答 正文

如何在Python中保存NLTK聊天机器人对话?

我用的是通用的,随处可见的NLTK。聊天机器人教程中的聊天代码。它工作得很完美,但我想把每个对话保存到一个文本文件。我通过NLTK.chat搜索。util和NLTK。聊天文档,找不到任何导出方法。有人知道怎么做吗? 下面是示例代码:

from nltk.chat.util import Chat, reflections

pairs = [
    ['my name is (.*)', ["hi %1"]],
    ["(hi|hello|hey)", ["hey there", "hello", "sup"]],
    ["(.*) your name", ["My name is S.H.A.N.E."]],
    ["(how are you|how are you feeling)", ["I'm doing well, thank you."]]
]

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

问题来源StackOverflow 地址:/questions/59383586/how-to-save-nltk-chatbot-conversations-in-python

展开
收起
kun坤 2019-12-27 10:16:48 637 分享 版权
阿里云 AI 助理回答

NLTK的chat模块本身确实没有直接提供保存对话记录到文件的功能,但你可以通过自定义代码来实现这一需求。你可以在Chat.converse()方法调用时,捕获并处理用户输入和机器人的响应,然后将这些信息写入到一个文本文件中。下面是一个示例代码,展示了如何修改你的原有代码以实现这个功能:

from nltk.chat.util import Chat, reflections

pairs = [
    ['my name is (.*)', ["hi %1"]],
    ["(hi|hello|hey)", ["hey there", "hello", "sup"]],
    ["(.*) your name", ["My name is S.H.A.N.E."]],
    ["(how are you|how are you feeling)", ["I'm doing well, thank you."]]
]

chat = Chat(pairs, reflections)

# 定义一个函数来保存对话到文件
def save_conversation_to_file(filename):
    with open(filename, 'a') as file:
        file.write(f"User: {input}\n")
        file.write(f"Bot: {response}\n\n")

# 自定义converse方法以保存对话
def converse_and_save(chat_instance, filename='conversation.txt'):
    print("Let's chat! Type 'quit' to exit.")
    while True:
        input = input("> ")
        if input.lower() == 'quit':
            break
        response = chat_instance.respond(input)
        print(response)
        # 保存对话到文件
        save_conversation_to_file(filename)

converse_and_save(chat)

这段代码首先定义了一个save_conversation_to_file函数,用于接收用户输入和机器人响应,并将其追加到指定的文本文件中。然后,我们创建了一个新的converse_and_save函数,它在每次交互后调用save_conversation_to_file函数,从而实现了对话的自动保存。

请注意,这里的'conversation.txt'是默认的文件名,你可以根据需要更改它。此外,由于使用了with open语句,文件会在每次写入后自动关闭,确保数据安全地被保存。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答