按字符分割
在实现检索增强生成(RAG)时,一个关键步骤是将文档拆分为若干片段,并存入向量数据库。
LangChain 提供了多种分割策略,复杂度各不相同。本练习中,您将实现一种「按字符分割」的文本分割器,它依据字符来切分文档,并以字符数来衡量片段长度。
请记住:没有放之四海而皆准的分割策略。为了契合您的使用场景,您可能需要多做几次尝试与对比。
本练习是课程的一部分
使用 LangChain 开发 LLM 应用
练习说明
- 从
langchain_text_splitters导入CharacterTextSplitter类。 - 使用
separator="\n"、chunk_size=24、chunk_overlap=10创建一个CharacterTextSplitter实例。 - 使用
.split_text()方法分割quote,并打印各片段及其长度。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the 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 = CharacterTextSplitter(
separator=____,
chunk_size=____,
chunk_overlap=____)
# Split the string and print the chunks
docs = splitter.____(quote)
print(docs)
print([len(doc) for doc in docs])