← 返回教程目录
第 4 章 · 第 1 节 LDA 主题分析

文本预处理:停用词 / 分词

Preprocessing: Stopwords & Tokenization

老板们最常踩的坑:拿到 10 万条评论直接跑 LDA,跑出来全是无意义主题。问题不在算法,在数据。这一节搞定 LDA 前的所有预处理。

1. 标准预处理 4 步

import re


import jieba





def preprocess(text):


    # 1. 去 URL


    text = re.sub(r'http\S+', '', text)


    # 2. 去 @用户


    text = re.sub(r'@\S+', '', text)


    # 3. 去 emoji 和特殊字符


    text = re.sub(r'[^\u4e00-\u9fff\w\s]', '', text)


    # 4. 去多余空白


    text = re.sub(r'\s+', ' ', text).strip()


    return text

2. 中文分词(jieba)

import jieba





text = '这款手机拍照很清晰,续航也给力'


words = jieba.lcut(text)


# → ['这款', '手机', '拍照', '很', '清晰', ',', '续航', '也', '给力']





# 加载自定义词典(品牌名、专业术语)


jieba.load_userdict('my_dict.txt')


# my_dict.txt 内容(每行: 词 词频 词性):


# 小米手机 1000 n


# 鸿蒙系统 800 n

3. 停用词表(关键!)

# 加载哈工大停用词表(2000+ 词)


with open('stopwords_hit.txt', encoding='utf-8') as f:


    stopwords = set(f.read().splitlines())





# 自定义补充


custom_stop = {'感觉', '觉得', '应该', '可能', '可以', '比较', '真的'}


stopwords |= custom_stop





# 过滤


words_clean = [w for w in jieba.lcut(text) if w not in stopwords and len(w) > 1]


# → ['手机', '拍照', '清晰', '续航', '给力']
停用词决定了 LDA 主题质量:默认停用词表只有 300 词,不够用。哈工大版 2000 词、百度版 3500 词都更准。我们的 LDA 软件内置5 个领域停用词表(电商、微博、资讯、行业、政务)。

4. 批量处理 + 保存

import pandas as pd





df = pd.read_csv('comments_50k.csv')





def process(text):


    text = preprocess(str(text))


    words = jieba.lcut(text)


    return [w for w in words if w not in stopwords and len(w) > 1]





df['tokens'] = df['text'].apply(process)


df = df[df['tokens'].apply(len) >= 3]  # 至少 3 个词


df.to_pickle('comments_processed.pkl')  # pickle 保留 list 格式

5. 低频词 / 高频词过滤(可选但推荐)

from collections import Counter





all_words = [w for tokens in df['tokens'] for w in tokens]


freq = Counter(all_words)





# 去掉出现 < 5 次的(罕见词)


# 去掉出现 > 50% 文档的(太常见,无区分度)


def filter_words(tokens):


    return [w for w in tokens if 5 <= freq[w] <= 0.5 * len(df)]





df['tokens'] = df['tokens'].apply(filter_words)

预处理好的语料,下一节就可以直接喂给 LDA 了。

5 万条评论预处理太慢?LDA 主题软件内置并行,5 万条 30 秒跑完

配套软件内置案例数据 + 模板,导入即出图,无需写代码

查看淘宝软件 →