前言
为什么你精心构建的 RAG 系统,返回的答案却总是“不着调”?不是模型不够强,而是你没“切”对!
RAG(检索增强生成)系统的精髓,不在于你用了哪个 embedding 模型,也不在于你接入了哪个 LLM,而在于——你如何「切」文本。切得好,信息上下文完整、检索精准;切不好,模型不是“胡说八道”,就是“词不达意”。
今天就来带你一次性掌握 15种最实用的 RAG 分块技巧,每种方法都配有真实场景和分块示例,甚至直接可用的代码结构。建议收藏 + 实战验证!
1. 按行切分(Line-by-Line Chunking)
适用场景: 聊天记录、逐行转录、问答型文本
推荐理由: 每行是一段完整语义,便于精确检索。
def line_chunk(text): return [line.strip() for line in text.strip().split('\n') if line.strip()]
输入示例:
Alice: Hey Bob, are you free for a call at 3 PM today?Bob: Sure, Alice. Do you want to discuss the project updates?Alice: Yes, and we need to talk about the client meeting.Bob: Sounds good! See you at 3.
分块结果:
CHUNK1: Alice: Hey Bob, are you free for a call at 3 PM today?CHUNK2: Bob: Sure, Alice. Do you want to discuss the project updates?CHUNK3: Alice: Yes, and we need to talk about the client meeting.CHUNK4: Bob: Sounds good! See you at 3.
⚠️注意: 如果每行太短,容易导致模型缺乏上下文,出现幻觉。
2. 固定大小切分(Fixed-Size Chunking)
适用场景: 无结构、无标点文本如OCR、爬虫原始内容
推荐理由: 保证块均匀,便于存储和处理
def fixed_chunk(text, size=20): words = text.split() return [' '.join(words[i:i+size]) for i in range(0, len(words), size)]
输入文本:
Python is a high-level, interpreted programming language...
代码实现:
import textwrapdef fixed_chunk(text, size=20): words = text.split() chunks = [' '.join(words[i:i+size]) for i in range(0, len(words), size)] return chunks
输出(每20词一块):
CHUNK1: Python is a high-level, interpreted programming language...CHUNK2: ...paradigms, including structured, object-oriented, and functional...
3. 滑动窗口切分(Sliding Window Chunking)
适用场景: 句意跨行的文本,如技术文档、合同
推荐理由: 保留上下文,防止语义断裂
Python 示例:
def sliding_window_chunk(text, size=15, overlap=5): words = text.split() chunks = [] for i in range(0, len(words) - size + 1, size - overlap): chunk = ' '.join(words[i:i + size]) chunks.append(chunk) return chunks
4. 按句子切分(Sentence-Based Chunking)
适用场景: 清洗过的文章、教材、技术博客
推荐理由: 每句是独立语义,利于拼接重组
import nltknltk.download('punkt')from nltk.tokenize import sent_tokenize
def sentence_chunk(text): return sent_tokenize(text)
示例输入:
Deep learning has transformed many fields of technology. Neural networks...
输出:
CHUNK1: Deep learning has transformed many fields of technology.CHUNK2: Neural networks can now outperform humans in image recognition.
5. 按段落切分(Paragraph Chunking)
适用场景: 博客、论文、演讲稿
推荐理由: 段落天然是完整语义单元
def paragraph_chunk(text): return [p.strip() for p in text.strip().split('\n\n') if p.strip()]
代码逻辑:
def paragraph_chunk(text): return text.strip().split('\n\n') # 假设段落间有空行
6. 按页切分(Page-Based Chunking)
适用场景: PDF、扫描文档、合同
推荐理由: 页码在文档中具有检索价值(如法院文件)
def page_chunk(text): return [page.strip() for page in text.strip().split('\f') if page.strip()] # 使用 \f 分页符
7. 按标题或小节切分(Section or Heading Chunking)
适用场景: Markdown 文档、说明书、白皮书
import re
def section_chunk(text): chunks = [] sections = re.split(r'(?m)^#+\s+', text) headings = re.findall(r'(?m)^#+\s+(.*)', text) for i, section in enumerate(sections[1:]): chunks.append(f"# {headings[i]}\n{section.strip()}") return chunks
示例输入:
# IntroductionRAG allows LLMs to use external knowledge.# How RAG WorksRAG retrieves context and then generates.
输出:
CHUNK1: # Introduction \n RAG allows LLMs to use external knowledge.CHUNK2: # How RAG Works \n RAG retrieves context and then generates.
8. 关键词切分(Keyword-Based Chunking)
适用场景: 医疗记录、操作手册、FAQ
逻辑: 遇到关键词(如“Note:”、“Step”)即切断
def keyword_chunk(text, keywords=["Note:", "Step", "Q:", "A:"]): import re pattern = '|'.join([re.escape(k) for k in keywords]) parts = re.split(f'(?=\\b({pattern}))', text) return [''.join(parts[i:i+2]).strip() for i in range(0, len(parts), 2)]
9. 实体切分(Entity-Based Chunking)
适用场景: 新闻、评论、法律文书
方法: 使用 NER 工具提取实体,按实体聚合内容
Python 示例(用 spaCy):
import spacynlp = spacy.load("en_core_web_sm")doc = nlp(text)for ent in doc.ents: print(ent.text, ent.label_)
10. Token切分(Token-Based Chunking)
适用场景: 控制 LLM 输入大小,防止上下文超长
工具: 使用 tiktoken
计算 Token 数量
import tiktoken
def token_chunk(text, max_tokens=200, model="gpt-3.5-turbo"): enc = tiktoken.encoding_for_model(model) tokens = enc.encode(text) chunks = [tokens[i:i+max_tokens] for i in range(0, len(tokens), max_tokens)] return [enc.decode(chunk) for chunk in chunks]
11. 表格切分(Table Chunking)
适用场景: 财报、研究论文、发票
方法: 整张表作为一块,或者逐行切分,结合周围文字
def table_chunk(text): tables = [] blocks = text.split('\n\n') for block in blocks: lines = block.strip().split('\n') if all('|' in line for line in lines): # 简单判断为表格 tables.append(block) return tables
12. 递归切分(Recursive Chunking)
适用场景: 内容结构不均的文本(长段落 + 短句混合)
策略: 先大后小,从段落 → 句子 → 词语,直到符合 chunk 限制
def recursive_chunk(text, max_words=100): if len(text.split()) <= max_words: return [text] paragraphs = text.split('\n\n') chunks = [] for p in paragraphs: if len(p.split()) > max_words: sentences = sent_tokenize(p) current = [] for s in sentences: current.append(s) if len(' '.join(current).split()) >= max_words: chunks.append(' '.join(current)) current = [] if current: chunks.append(' '.join(current)) else: chunks.append(p) return chunks
13. 语义切分(Semantic Chunking)
适用场景: FAQ、客服日志、知识库
方法: 利用 embedding 聚类,按语义相近分组
from sklearn.cluster import KMeansfrom sentence_transformers import SentenceTransformer
def semantic_chunk(text, n_clusters=5): model = SentenceTransformer('all-MiniLM-L6-v2') sentences = sent_tokenize(text) embeddings = model.encode(sentences) kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(embeddings) clusters = [[] for _ in range(n_clusters)] for i, label in enumerate(kmeans.labels_): clusters[label].append(sentences[i]) return [' '.join(cluster) for cluster in clusters]
14. 层级切分(Hierarchical Chunking)
适用场景: 教材、法规、文档规范
方法: 按“章节 → 小节 → 段落”三层结构分割
def hierarchical_chunk(text): # 简单模拟:标题 => 小节 => 段落 levels = re.split(r'(#+\s.*)', text) result = [] for i in range(1, len(levels), 2): section = levels[i].strip() + '\n' + levels[i+1].strip() result.append(section) return result
15. 内容类型感知切分(Content-Type Aware Chunking)
适用场景: 图文混合PDF、科研报告、年报
策略: 图、表、正文、列表各自为块,避免混淆格式
def content_type_chunk(text): chunks = [] lines = text.splitlines() buffer = [] current_type = None
def flush(): if buffer: chunks.append('\n'.join(buffer)) buffer.clear()
for line in lines: if re.match(r'^\s*\|.*\|\s*$', line): if current_type != 'table': flush() current_type = 'table' elif re.match(r'^#+\s+', line): if current_type != 'heading': flush() current_type = 'heading' elif re.match(r'^[-*]\s+', line): if current_type != 'list': flush() current_type = 'list' else: if current_type != 'text': flush() current_type = 'text' buffer.append(line) flush() return chunks
📌总结:一张图快速回顾 15 种分块方式
编号 | 分块方式 | 最适用场景 | 是否语义保持 | 实现难度 |
---|---|---|---|---|
1 | 按行切分 | 聊天记录、逐行转录 | ✅ | 🟢低 |
2 | 固定词数 | OCR、爬虫数据 | ❌ | 🟢低 |
3 | 滑动窗口 | 技术文档、连贯句 | ✅✅ | 🟡中 |
4 | 按句子 | 教材、博客 | ✅ | 🟢低 |
5 | 按段落 | 正式文章 | ✅✅ | 🟢低 |
6 | 按页 | PDF、法律合同 | ✅ | 🟢低 |
7 | 按标题/小节 | 文档、白皮书 | ✅✅ | 🟢低 |
8 | 关键词触发 | 表单、医疗记录 | ✅ | 🟡中 |
9 | 实体识别分组 | 新闻、评论 | ✅✅ | 🟡中 |
10 | Token限制 | 所有LLM处理 | ✅ | 🟡中 |
11 | 表格单独分块 | 财报、学术报告 | ✅✅ | 🟡中 |
12 | 递归切分 | 结构混乱文档 | ✅✅ | 🔴高 |
13 | 语义聚类 | FAQ、知识库 | ✅✅✅ | 🔴高 |
14 | 多层级结构切分 | 教材、技术文档 | ✅✅✅ | 🔴高 |
15 | 内容类型感知 | 图文混合PDF | ✅✅ | 🔴高 |
结语:选对“切法”,LLM 才能答对问题
构建 RAG 系统时,最容易被忽略、却最影响效果的关键环节,往往是「Chunking」。
别再盲目用默认的 chunk 大小了。回顾你的数据结构,选择合适的分块策略,才能让 RAG 如虎添翼,检索又准又稳!
最后
为什么要学AI大模型
当下,⼈⼯智能市场迎来了爆发期,并逐渐进⼊以⼈⼯通⽤智能(AGI)为主导的新时代。企业纷纷官宣“ AI+ ”战略,为新兴技术⼈才创造丰富的就业机会,⼈才缺⼝将达 400 万!
DeepSeek问世以来,生成式AI和大模型技术爆发式增长,让很多岗位重新成了炙手可热的新星,岗位薪资远超很多后端岗位,在程序员中稳居前列。
与此同时AI与各行各业深度融合,飞速发展,成为炙手可热的新风口,企业非常需要了解AI、懂AI、会用AI的员工,纷纷开出高薪招聘AI大模型相关岗位。
最近很多程序员朋友都已经学习或者准备学习 AI 大模型,后台也经常会有小伙伴咨询学习路线和学习资料,我特别拜托北京清华大学学士和美国加州理工学院博士学位的鲁为民老师给大家这里给大家准备了一份涵盖了AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频 全系列的学习资料,这些学习资料不仅深入浅出,而且非常实用,让大家系统而高效地掌握AI大模型的各个知识点。
这份完整版的大模型 AI 学习资料已经上传优快云,朋友们如果需要可以微信扫描下方优快云官方认证二维码免费领取【保证100%免费
】

AI大模型系统学习路线
在面对AI大模型开发领域的复杂与深入,精准学习显得尤为重要。一份系统的技术路线图,不仅能够帮助开发者清晰地了解从入门到精通所需掌握的知识点,还能提供一条高效、有序的学习路径。
但知道是一回事,做又是另一回事,初学者最常遇到的问题主要是理论知识缺乏、资源和工具的限制、模型理解和调试的复杂性,在这基础上,找到高质量的学习资源,不浪费时间、不走弯路,又是重中之重。
AI大模型入门到实战的视频教程+项目包
看视频学习是一种高效、直观、灵活且富有吸引力的学习方式,可以更直观地展示过程,能有效提升学习兴趣和理解力,是现在获取知识的重要途径
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
海量AI大模型必读的经典书籍(PDF)
阅读AI大模型经典书籍可以帮助读者提高技术水平,开拓视野,掌握核心技术,提高解决问题的能力,同时也可以借鉴他人的经验。对于想要深入学习AI大模型开发的读者来说,阅读经典书籍是非常有必要的。
600+AI大模型报告(实时更新)
这套包含640份报告的合集,涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。
AI大模型面试真题+答案解析
我们学习AI大模型必然是想找到高薪的工作,下面这些面试题都是总结当前最新、最热、最高频的面试题,并且每道题都有详细的答案,面试前刷完这套面试题资料,小小offer,不在话下
这份完整版的大模型 AI 学习资料已经上传优快云,朋友们如果需要可以微信扫描下方优快云官方认证二维码免费领取【保证100%免费
】
