跳到主要內容
Open In ColabOpen on GitHub

如何以字元遞迴分割文字

文字分割器是通用文字的建議選擇。它由字元列表參數化。它會依序嘗試分割它們,直到區塊足夠小。預設列表為 ["\n\n", "\n", " ", ""]。這樣做的效果是盡可能將所有段落(然後是句子,然後是單字)保持在一起,因為這些通常看起來是語意上最強相關的文字片段。

  1. 文字的分割方式:依字元列表。
  2. 區塊大小的測量方式:依字元數。

以下我們顯示範例用法。

若要直接取得字串內容,請使用 .split_text

若要建立 LangChain Document 物件(例如,用於下游任務),請使用 .create_documents

%pip install -qU langchain-text-splitters
from langchain_text_splitters import RecursiveCharacterTextSplitter

# Load example document
with open("state_of_the_union.txt") as f:
state_of_the_union = f.read()

text_splitter = RecursiveCharacterTextSplitter(
# Set a really small chunk size, just to show.
chunk_size=100,
chunk_overlap=20,
length_function=len,
is_separator_regex=False,
)
texts = text_splitter.create_documents([state_of_the_union])
print(texts[0])
print(texts[1])
page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and'
page_content='of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.'
text_splitter.split_text(state_of_the_union)[:2]
['Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and',
'of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.']

讓我們來看看上面為 RecursiveCharacterTextSplitter 設定的參數

  • chunk_size:區塊的最大大小,其中大小由 length_function 決定。
  • chunk_overlap:區塊之間的目標重疊。重疊區塊有助於減輕在區塊之間劃分上下文時資訊的遺失。
  • length_function:決定區塊大小的函數。
  • is_separator_regex:分隔符號列表(預設為 ["\n\n", "\n", " ", ""])是否應解釋為 regex。

從沒有單字邊界的語言分割文字

有些書寫系統沒有單字邊界,例如中文、日文和泰文。使用預設分隔符號列表 ["\n\n", "\n", " ", ""] 分割文字可能會導致單字在區塊之間被分割。為了保持單字完整,您可以覆寫分隔符號列表以包含其他標點符號

  • 新增 ASCII 句點 "."、Unicode 全形句點 ""(用於中文文字)和 表意文字句點 ""(用於日文和中文)
  • 新增泰文、緬甸文、高棉文和日文使用的零寬度空格
  • 新增 ASCII 逗號 ","、Unicode 全形逗號 "" 和 Unicode 表意文字逗號 ""
text_splitter = RecursiveCharacterTextSplitter(
separators=[
"\n\n",
"\n",
" ",
".",
",",
"\u200b", # Zero-width space
"\uff0c", # Fullwidth comma
"\u3001", # Ideographic comma
"\uff0e", # Fullwidth full stop
"\u3002", # Ideographic full stop
"",
],
# Existing args
)

此頁面是否有幫助?