清华开源ChatGPT自动编程ChatDev项目documents.py代码解读

以下是对”documents.py“代码的详细解析和添加注释:

import re
import os
import time
from colorama import Fore

class Documents():
    def __init__(self, generated_content="", parse=True, predifined_filename=None):
        self.directory: str = None  # 存放文档的目录路径
        self.generated_content = generated_content  # 生成的内容
        self.docbooks = {}  # 存放文档的字典,键为文件名,值为文档内容

        if generated_content != "":
            if parse:
                regex = r"```\n(.*?)```"  # 用于匹配文档内容的正则表达式模式
                matches = re.finditer(regex, self.generated_content, re.DOTALL)
                for match in matches:
                    filename = "requirements.txt"  # 默认的文件名
                    doc = match.group(1)  # 匹配到的文档内容
                    self.docbooks[filename] = doc  # 将文档内容存入字典
            else:
                self.docbooks[predifined_filename] = self.generated_content  # 将生成的内容存入字典,使用预定义的文件名

    def _update_docs(self, generated_content, parse=True, predifined_filename=""):
        new_docs = Documents(generated_content, parse, predifined_filename)  # 创建一个新的Documents对象
        for key in new_docs.docbooks.keys():
            if key not in self.docbooks.keys() or self.docbooks[key] != new_docs.docbooks[key]:
                print("{} updated.".format(key))  # 打印更新的文件名
                print(Fore.WHITE + "------Old:\n{}\n------New:\n{}".format(
                    self.docbooks[key] if key in self.docbooks.keys() else "# None", new_docs.docbooks[key]))  # 打印旧内容和新内容
                self.docbooks[key] = new_docs.docbooks[key]  # 更新文档内容

    def _rewrite_docs(self):
        directory = self.directory
        if not os.path.exists(directory):  # 如果目录不存在,则创建目录
            os.mkdir(directory)
            print("{} Created.".format(directory))
        for filename in self.docbooks.keys():
            with open(os.path.join(directory, filename), "w", encoding="utf-8") as writer:  # 将文档内容写入文件
                writer.write(self.docbooks[filename])
                print(os.path.join(directory, filename), "Writed")

    def _get_docs(self):
        content = ""
        for filename in self.docbooks.keys():  # 将所有文档内容拼接成字符串
            content += "{}\n```\n{}\n```\n\n".format(filename, self.docbooks[filename])
        return content  # 返回文档内容的字符串表示

代码主要定义了一个Documents类,用于管理生成的文档。其中包含以下方法:

  • __init__(self, generated_content="", parse=True, predifined_filename=None):类的构造方法,初始化Documents对象。
  • _update_docs(self, generated_content, parse=True, predifined_filename=""):更新文档内容。
  • _rewrite_docs(self):将文档内容写入文件。
  • _get_docs(self):返回文档内容的字符串表示。

该类的功能是根据生成的内容,管理和处理文档的保存、更新和获取操作。

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注