← 返回教程目录
第 8 章 · 第 1 节 数据清洗

正则去噪:HTML 标签 / URL / @用户 / Emoji

Regex Cleaning: HTML, URL, @Mentions, Emoji

原始评论 90% 是脏数据 — 包含 HTML 残留、URL、@用户、emoji、广告。这些不清理,后续分词/词频全是垃圾。

1. 12 项清洗规则

import re





def clean_text(text):


    if not isinstance(text, str):


        return ''


    text = re.sub(r'<[^>]+>', '', text)


    text = re.sub(r'https?://\S+', '', text)


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


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


    emoji_pattern = re.compile(


        "[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F1E0-\U0001F1FF]+",


        flags=re.UNICODE


    )


    text = emoji_pattern.sub('', text)


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


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


    return text.strip()





raw = '  这款手机@小米 真心不错!http://t.cn/abc123  👍👍
' print(clean_text(raw)) # '这款手机 真心不错'
清洗深度要看场景:分析情感时 emoji 是重要信号(用户表达情绪),不应该删;做关键词统计时 emoji 是噪声,要删。规则是能配的。

2. 批量清洗 + 进度条

from tqdm import tqdm


tqdm.pandas()





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


df['clean'] = df['content'].progress_apply(clean_text)


df = df[df['clean'].str.len() > 5]


df.to_csv('comments_clean.csv', index=False)


print(f'清洗后剩 {len(df)} 条')

10 万条评论,这套流水线跑下来 30 秒。下一节我们加上去重。

想跳过写代码,直接清洗 10 万条评论?

配套软件内置 12 项清洗规则 + 批量改名,导入即出干净语料

查看淘宝软件 →