0Pricing
LangChain / RAG / Vector DBs · บทเรียน

การปรับแต่งการแบ่งเอกสาร

นำเทคนิคการแบ่งข้อความขั้นสูงมาใช้ รวมถึงการแบ่งเป็นส่วนตามความหมาย และการจัดการโค้ดหรือโครงสร้างข้อมูลเฉพาะ

การปรับแต่งการแบ่งเอกสาร เป็นบทเรียน LangChain / RAG / Vector DBs ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน LangChain / RAG / Vector DBs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Customize Text Splitting?

When preparing documents for Retrieval Augmented Generation (RAG), how you split them into chunks is crucial. Basic text splitters are a good start, but they often fall short for complex or highly structured content.

Customizing your text splitting strategy allows you to maintain better contextual integrity, leading to more accurate retrievals and better LLM responses.

Tailoring Character Splitters

LangChain's CharacterTextSplitter is simple but powerful. You can customize it by providing specific separator characters. This is useful when your documents have unique delimiters you want to respect, like a specific tag or a unique line break pattern.

By defining your own separators, you can ensure logical breaks rather than arbitrary character counts.

from langchain.text_splitter import CharacterTextSplitter

class Main:
    def run(self):
        text = "Chapter 1: Intro.Section 1.1: Basics.Section 1.2: Advanced."
        # Custom separator is "."
        splitter = CharacterTextSplitter(
            separator=".",
            chunk_size=20,
            chunk_overlap=0
        )
        chunks = splitter.split_text(text)
        for i, chunk in enumerate(chunks):
            print(f"Chunk {i+1}: {chunk}")

if __name__ == "__main__":
    Main().run()

Refining Recursive Splitters

The RecursiveCharacterTextSplitter attempts to split text using a list of separators in order, trying to keep chunks as large as possible. You can customize this list to match your document's inherent structure.

For example, you might prioritize splitting by double newlines, then single newlines, then spaces, and finally characters.

from langchain.text_splitter import RecursiveCharacterTextSplitter

class Main:
    def run(self):
        text = "Hello there!\n\nThis is a paragraph.\nAnd this is another sentence."
        # Custom list of separators
        splitter = RecursiveCharacterTextSplitter(
            separators=["\n\n", "\n", " ", ""],
            chunk_size=40,
            chunk_overlap=0
        )
        chunks = splitter.split_text(text)
        for i, chunk in enumerate(chunks):
            print(f"Chunk {i+1}: {chunk}")

if __name__ == "__main__":
    Main().run()

Intro to Semantic Chunking

Instead of relying solely on character counts or delimiters, what if we could split text based on its meaning?

Semantic chunking aims to create chunks that represent complete, coherent ideas or topics. This method helps prevent important concepts from being arbitrarily split across different chunks, which often happens with fixed-size or simple character splitters.

How Semantic Chunking Works

Semantic chunking typically involves a few steps:

  • Embed Sentences: Each sentence or a small unit of text is converted into a vector embedding.
  • Measure Similarity: The semantic similarity between adjacent sentences or units is measured using their embeddings.
  • Identify Breakpoints: Chunks are formed where semantic similarity drops significantly, indicating a topic change or a shift in discussion.

While LangChain doesn't have a single 'semantic splitter' out-of-the-box, it's a pattern you can build using embedding models and custom logic.

Specialized Code Splitters

Code has a unique structure, with functions, classes, comments, and specific syntax. Generic text splitters often break code in awkward places, making the resulting chunks hard to understand or use as context for an LLM.

LangChain provides specialized splitters for different programming languages. These splitters understand the syntax of a language and ensure that chunks are syntactically meaningful, like keeping a whole function or class together.

Python Code Splitter Demo

The RecursiveCharacterTextSplitter.from_language method allows you to specify a programming language. It then uses language-specific separators (like class definitions, function definitions, etc.) to create more intelligent chunks.

This ensures that code snippets passed to an LLM are more coherent.

from langchain.text_splitter import RecursiveCharacterTextSplitter, Language

class Main:
    def run(self):
        python_code = """
def calculate_sum(a, b):
    # This function adds two numbers
    return a + b

class MyCalculator:
    def __init__(self):
        self.result = 0

    def add(self, num):
        self.result += num

if __name__ == "__main__":
    total = calculate_sum(5, 3)
    print(f"Sum: {total}")
    calc = MyCalculator()
    calc.add(10)
    print(f"Calc result: {calc.result}")
"""

        # Initialize splitter for Python code
        python_splitter = RecursiveCharacterTextSplitter.from_language(
            language=Language.PYTHON,
            chunk_size=100, # Adjust chunk size to see more splits
            chunk_overlap=0
        )

        docs = python_splitter.create_documents([python_code])

        for i, doc in enumerate(docs):
            print(f"--- Chunk {i+1} ---")
            print(doc.page_content)

if __name__ == "__main__":
    Main().run()

Beyond Code: Other Structures

LangChain also offers specialized splitters for other structured formats, not just code:

  • MarkdownTextSplitter: Understands Markdown syntax (headings, code blocks, lists) to create logically grouped chunks.
  • LatexTextSplitter: Recognizes LaTeX sections, chapters, and environments, preserving the document's academic structure.

These specialized splitters are invaluable for processing documents where the formatting itself conveys important structural information.

Creating Custom Splitter Logic

For truly unique document structures or proprietary data formats, you might need to implement your own splitting logic. LangChain allows you to:

  • Subclass TextSplitter: Create a new class that inherits from TextSplitter and overrides its methods to define custom splitting rules.
  • Write a custom function: Develop a function that takes your text and returns a list of chunks based on your specific parsing requirements.

This approach offers maximum flexibility to handle complex regex patterns, custom delimiters, or nested structures unique to your dataset.

Check Your Understanding

You've learned about various ways to customize text splitting for different document types. Let's test your knowledge.

Custom Splitting Recap

In this lesson, we explored how to go beyond basic text splitting to handle diverse and complex document types more effectively:

  • We customized Character and Recursive Character splitters with specific lists of separators.
  • We introduced the concept of Semantic Chunking for meaning-based splits.
  • We learned about Language-specific splitters for code (e.g., Python, Java) and other structured formats like Markdown and LaTeX.
  • Finally, we discussed the power and flexibility of creating entirely custom splitting logic for unique data.

Mastering customized splitting strategies is a critical step in building accurate and robust RAG applications.

คำถามที่พบบ่อย

บทเรียน “การปรับแต่งการแบ่งเอกสาร” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การปรับแต่งการแบ่งเอกสาร” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส LangChain / RAG / Vector DBs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การปรับแต่งการแบ่งเอกสาร”

นำเทคนิคการแบ่งข้อความขั้นสูงมาใช้ รวมถึงการแบ่งเป็นส่วนตามความหมาย และการจัดการโค้ดหรือโครงสร้างข้อมูลเฉพาะ คุณปฏิบัติ LangChain / RAG / Vector DBs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน LangChain / RAG / Vector DBs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน LangChain / RAG / Vector DBs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การปรับแต่งการแบ่งเอกสาร” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน LangChain / RAG / Vector DBs นี้ได้ไหม

ได้ บทเรียน LangChain / RAG / Vector DBs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การโหลดเอกสารหลากหลายประเภท
  2. ทำความเข้าใจกลยุทธ์การแบ่งข้อความ
  3. การปรับแต่งการแบ่งเอกสาร
  4. การจัดการข้อมูลกำกับเอกสารและการกรอง
← กลับไปที่ LangChain / RAG / Vector DBs