在自然语言处理(NLP)项目中,原始文本数据往往包含大量无实际意义的词汇,这些词汇不仅会增加计算负担,还可能影响模型对关键信息的捕捉。中文文本尤其如此,像"的"、"了"、"啊"这类高频虚词几乎出现在每个句子中,但对语义理解帮助有限。这就是为什么我们需要进行文本清洗,而停用词表就是最常用的工具之一。
哈工大停用词表是国内公认比较权威的中文停用词集合,收录了1200多个常见停用词。我第一次使用这个词表是在做一个电商评论情感分析项目时,原始准确率只有78%,清洗掉停用词后直接提升到83%。这让我深刻体会到,好的数据预处理往往比复杂的模型调参更有效。
哈工大停用词表可以从其语言技术平台(LTP)官网下载,也可以直接使用我整理好的版本。这个词表采用UTF-8编码,每行一个停用词,格式非常规整。建议新建一个stopwords文件夹专门存放这类资源文件。
python复制# 停用词表示例片段
啊
阿
哎
哎呀
哎哟
唉
俺
俺们
按
按照
推荐使用Python 3.6+版本,主要依赖库是jieba(用于中文分词)和tqdm(进度条显示)。如果你用Anaconda,可以直接用以下命令安装:
bash复制pip install jieba tqdm
我习惯在代码开头统一设置编码,避免中文路径问题:
python复制# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
这里有个坑要注意:不同操作系统下的文件路径写法不同。我在Windows和Mac上都测试过,建议使用os.path.join来处理路径:
python复制import os
from tqdm import tqdm
def load_stopwords(stopwords_path):
stopwords = []
with open(stopwords_path, 'r') as f:
for line in f:
stopwords.append(line.strip())
return set(stopwords) # 转成集合提高查询效率
实际项目中我发现,单纯删除停用词还不够,还需要处理标点符号和特殊字符。下面这个增强版函数是我经过多个项目优化的:
python复制import re
import jieba
def clean_text(text, stopwords):
# 去除HTML标签
text = re.sub(r'<[^>]+>', '', text)
# 去除特殊字符
text = re.sub(r'[^\w\s]', '', text)
# 分词
words = jieba.cut(text)
# 过滤停用词
return [word for word in words if word not in stopwords and len(word) > 1]
当需要处理成百上千个文件时,这个批量处理函数能显示进度条,非常实用:
python复制def process_files(input_dir, output_dir, stopwords):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
files = [f for f in os.listdir(input_dir) if f.endswith('.txt')]
for filename in tqdm(files):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
with open(input_path, 'r') as infile, open(output_path, 'w') as outfile:
text = infile.read()
cleaned_words = clean_text(text, stopwords)
outfile.write(' '.join(cleaned_words))
以电商评论为例,原始评论可能是:"这个手机真的很好用,但是价格有点贵啊!"经过清洗后会变成:"手机 很好用 价格 贵"。可以看到,情感关键词被保留了下来,而干扰词都被过滤了。
我在实际项目中对比过,使用停用词表后:
当处理大规模文本时,我有几个实用建议:
python复制from multiprocessing import Pool
def parallel_clean(args):
filepath, stopwords = args
# 清洗逻辑...
# 使用4个进程
with Pool(4) as p:
results = list(tqdm(p.imap(parallel_clean, tasks), total=len(tasks)))
哈工大停用词表虽然全面,但具体项目可能需要调整。比如做法律文本分析时,"本法"、"条"可能是关键词而非停用词。我的经验是:
保存自定义词表建议用JSON格式,方便维护:
python复制import json
# 保存
with open('custom_stopwords.json', 'w') as f:
json.dump(list(stopwords), f)
# 加载
with open('custom_stopwords.json', 'r') as f:
stopwords = set(json.load(f))
处理中文文本数据时,我最大的体会是:没有放之四海而皆准的停用词表。在最近的一个医疗问答系统项目中,标准停用词表反而过滤掉了"患者"、"症状"等关键术语。后来我们通过领域词典+自动筛选的方式,重新构建了适合医疗场景的停用词表,准确率提升了12%。所以建议大家在项目初期就要重视数据探索,根据实际效果调整预处理策略。