按字符递归分割
许多开发者会使用递归字符分割器,按照一组特定字符来拆分文档。默认字符为段落换行、换行、空格和空字符串:["\n\n", "\n", " ", ""]。
分割器会优先尝试按段落拆分,检查是否满足 chunk_size 与 chunk_overlap 的要求;如果不满足,就按句子、再按词,最后按单个字符继续拆分。
通常,您需要尝试不同的 chunk_size 和 chunk_overlap 取值,才能找到适合您文档的配置。
本练习是课程的一部分
使用 LangChain 开发 LLM 应用
练习说明
- 从
langchain_text_splitters导入RecursiveCharacterTextSplitter类。 - 使用
separators=["\n", " ", ""]、chunk_size=24、chunk_overlap=10创建一个RecursiveCharacterTextSplitter实例。 - 使用
.split_text()方法分割quote,并打印分块及其长度。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the recursive character splitter
from langchain_text_splitters import ____
quote = 'Words are flowing out like endless rain into a paper cup,\nthey slither while they pass,\nthey slip away across the universe.'
chunk_size = 24
chunk_overlap = 10
# Create an instance of the splitter class
splitter = RecursiveCharacterTextSplitter(
separators=____,
chunk_size=____,
chunk_overlap=____)
# Split the document and print the chunks
docs = splitter.____(quote)
print(docs)
print([len(doc) for doc in docs])