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

使用Langchain的RecursiveCharacterTextSplitter后,如何为分片关联原文件名?

为RecursiveCharacterTextSplitter的分片关联文件名

问题根源

你当前的代码仅收集了文件的文本内容,没有同步保留文件名信息,导致拆分后的分片无法追溯到所属文件。

解决方案

读取文件时同时记录文件名(或相对路径),对每个文件单独执行拆分操作,并将文件名作为**元数据(metadata)**附加到每个分片对应的Document对象中。Langchain的Document原生支持携带元数据,能完美解决分片与源文件的关联问题。

修改后的完整代码

def index_repo(repo_url):
    os.environ['OPENAI_API_KEY'] = ""
    # 改为存储(文件相对路径, 文件内容)的元组列表
    file_data = []
    fileextensions = [".py"]

    print('cloning repo')
    repo_dir = get_repo(repo_url)
    print(repo_dir)

    for dirpath, dirnames, filenames in os.walk(repo_dir):
        for file in filenames:
            if file.endswith(tuple(fileextensions)):
                try:
                    full_path = os.path.join(dirpath, file)
                    # 存储相对于仓库根目录的路径,更便于识别文件位置
                    relative_path = os.path.relpath(full_path, repo_dir)
                    with open(full_path, "r", encoding="utf-8") as f:
                        file_data.append((relative_path, f.read()))
                except Exception as e:
                    print(f"读取文件 {relative_path} 失败: {str(e)}")
                    pass

    # 初始化文本拆分器
    text_splitter = RecursiveCharacterTextSplitter.from_language(
        language=Language.PYTHON, chunk_size=5000, chunk_overlap=0
    )

    split_docs = []
    for filename, content in file_data:
        # 为当前文件的所有分片添加元数据
        docs = text_splitter.create_documents(
            [content],
            metadatas=[{"source": filename}]  # 每个分片都会带上该元数据
        )
        split_docs.extend(docs)

    return split_docs

关键细节说明

  • 保留文件标识:用file_data列表存储(文件相对路径, 内容)的元组,确保每个文件的内容都能关联到唯一标识。
  • 元数据绑定:调用create_documents时,通过metadatas参数传入包含文件名的字典,每个分片的Document对象会自动带上metadata["source"]字段,后续可通过该字段直接获取分片所属的源文件。
  • 单文件拆分:遍历每个文件单独执行拆分,避免不同文件的内容混合,确保分片与源文件的对应关系绝对准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:16:03