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便于后续构建点击率统计特征。若需要处理其他中文语料这套方法稍作调整即可迁移比如针对微博数据需增加表情符号过滤步骤。