【Python NLP实战】:搜狗新闻语料清洗与结构化存储指南 1. 搜狗新闻语料库简介与数据准备搜狗新闻语料库是中文自然语言处理领域常用的开源数据集包含大量经过分类的新闻文本。原始数据以TXT文件格式存储采用ANSI编码每个文件包含多条新闻条目每条新闻由url、contenttitle和content三个标签包裹。为什么选择精简版我在实际处理时发现迷你版语料存在两个致命问题一是数据量过小无法反映真实分布二是部分文件存在标签残缺。建议直接下载约1.8GB的精简版解压后会得到一组命名如news_001.txt的文件。文件结构示例urlhttp://sports.sohu.com/20230715/n123456.shtml/url contenttitle中国女排夺得世界联赛冠军/contenttitle content北京时间7月15日2023年世界女排联赛总决赛...正文内容/content2. 环境配置与核心工具2.1 安装必要库推荐使用conda创建专属环境conda create -n nlp python3.8 conda activate nlp pip install regex pandas tqdm2.2 关键工具选择编码处理直接使用Python内置的decode(ansi)实测比chardet更高效正则表达式选用regex库而非标准re因其对多行匹配的性能更优文件操作结合os.makedirs的exist_ok参数避免重复创建目录3. 数据清洗实战步骤3.1 编码转换与文本提取原始ANSI编码需转换为UTF-8以避免乱码def read_file(file_path): with open(file_path, rb) as f: raw f.read().decode(ansi, errorsignore) # 忽略非法字符 return raw3.2 多级正则匹配使用非贪婪模式匹配新闻要素pattern rurl(.*?)/url.*?contenttitle(.*?)/contenttitle.*?content(.*?)/content news_items regex.findall(pattern, text, regex.DOTALL)常见坑点部分正文含换行符导致匹配失败 → 添加DOTALL标志URL中包含特殊字符 → 使用regex.escape()处理3.3 类别提取技巧从URL中提取新闻类别时我发现直接分割比正则更可靠def extract_category(url): try: return url.split(//)[1].split(.)[0] # 获取sports等域名前缀 except: return other4. 结构化存储方案4.1 目录结构设计采用类别/标题.txt的层次存储既方便后续按领域训练模型又避免单个目录文件过多。实现代码def save_news(category, title, content, output_dirsogou_structured): cat_dir os.path.join(output_dir, category) os.makedirs(cat_dir, exist_okTrue) # 处理非法文件名字符 safe_title regex.sub(r[\\/*?:|], _, title.strip()) file_path os.path.join(cat_dir, f{safe_title}.txt) with open(file_path, w, encodingutf-8) as f: f.write(content)4.2 质量过滤策略添加三个过滤条件提升数据质量标题非空且长度≤50字符正文长度≥100字符且≤5000字符类别不为空if (title and 0 len(title) 50 and 100 len(content) 5000 and category): save_news(category, title, content)5. 性能优化技巧5.1 内存管理处理大文件时采用分块读取def chunked_read(file_path, chunk_size1024*1024): with open(file_path, rb) as f: while chunk : f.read(chunk_size): yield chunk.decode(ansi, errorsignore)5.2 多进程加速利用multiprocessing.Pool并行处理from multiprocessing import Pool def process_file(file_path): # 处理单个文件的逻辑 pass with Pool(processes4) as pool: pool.map(process_file, file_list)6. 完整代码实现import os import regex from tqdm import tqdm class SogouProcessor: def __init__(self, input_dirsogoucs, output_dirsogou_structured): self.input_dir input_dir self.output_dir output_dir self.pattern regex.compile( rurl(.*?)/url.*?contenttitle(.*?)/contenttitle.*?content(.*?)/content, regex.DOTALL ) def process_all(self): files [f for f in os.listdir(self.input_dir) if f.endswith(.txt)] for file in tqdm(files, descProcessing files): self.process_file(os.path.join(self.input_dir, file)) def process_file(self, file_path): text self.read_file(file_path) for url, title, content in self.pattern.findall(text): category self.extract_category(url) if self.validate_item(title, content, category): self.save_news(category, title, content) # 其他方法同上...7. 后续应用建议清洗后的数据可用于文本分类利用新闻类别标签训练分类器关键词提取结合TF-IDF或TextRank算法主题建模使用LDA分析不同领域的主题分布我曾用处理后的数据训练一个新闻推荐系统关键是在存储时保留了原始URL便于后续构建点击率统计特征。若需要处理其他中文语料这套方法稍作调整即可迁移比如针对微博数据需增加表情符号过滤步骤。

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/9/23 4:54:42
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/9/24 14:25:52
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/9/24 14:49:33
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/9/23 8:01:38
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/9/24 14:28:18
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/9/24 11:09:24

日新闻

周新闻