문자 단위로 분할하기

LangChain은 텍스트를 분할하는 가장 간단한 방법입니다. 기본적으로 문자(기본값은 "\n\n")를 기준으로 분할하며 청크의 길이는 문자 수로 측정됩니다.

  1. 텍스트의 분할 방식: 개별 문자로 분할됩니다.
  2. 청크 크기의 측정 방식: 문자 수로 측정됩니다.

패키지 설치

%pip install -qU langchain-text-splitters

예시

with open('../../../state_of_the_union.txt') as f:
    state_of_the_union = f.read()
from langchain_text_splitters import CharacterTextSplitter

text_splitter = CharacterTextSplitter(        
    separator="\n\n",
    chunk_size=1000,
    chunk_overlap=200,
    length_function=len,
)
texts = text_splitter.create_documents([state_of_the_union])
print(texts[0])
page_content='Madam Speaker, Madam Vice President ...' lookup_str='' metadata={} lookup_index=0

이는 문서와 함께 메타데이터를 전달하는 예시입니다. 문서와 함께 메타데이터가 어떻게 분할되는지 주목해 주세요.

metadatas = [{"document": 1}, {"document": 2}]
documents = text_splitter.create_documents([state_of_the_union, state_of_the_union], metadatas=metadatas)
print(documents[0])
page_content='.. 텍스트 무시 ..' lookup_str='' metadata={'document': 1} lookup_index=0
text_splitter.split_text(state_of_the_union)[0]