Python爬虫实战㉑|Pandas文本处理,字符串清洗与关键词提取
·
author: 专注Python实战,分享爬虫与数据分析干货
title: Python爬虫实战㉑|Pandas文本处理,字符串清洗与关键词提取
update: 2026-04-26
tags: Python,Pandas,文本处理,str,正则表达式,关键词提取,字符串清洗
作者:专注Python实战,分享爬虫与数据分析干货
更新时间:2026年4月
适合人群:有Pandas基础、需要处理文本数据的开发者
前言:爬虫数据中,文本占80%
商品标题、用户评论、新闻正文、标签分类……全是文本。清洗文本是数据分析的关键一步。
一、Pandas字符串方法
1.1 基础操作
import pandas as pd
df = pd.DataFrame({
"标题": [" Python入门 ", " 爬虫实战", "数据分析 ", "机器学习"],
"价格": ["¥59.9", "¥49.9", "69.9元", "$79.9"],
"标签": ["Python,入门,编程", "爬虫,实战,数据", "分析,Pandas", "ML,AI,深度学习"],
})
# 去除空格
df["标题_clean"] = df["标题"].str.strip()
df["标题_clean"] = df["标题"].str.replace(r"\s+", " ", regex=True) # 多空格变单空格
# 大小写
df["标题_lower"] = df["标题"].str.lower()
df["标题_upper"] = df["标题"].str.upper()
df["标题_title"] = df["标题"].str.title() # 首字母大写
# 长度
df["标题长度"] = df["标题"].str.len()
# 包含检测
df["含Python"] = df["标题"].str.contains("Python", case=False, na=False)
df["以入门结尾"] = df["标题"].str.endswith("入门")
df["以爬虫开头"] = df["标题"].str.startswith("爬虫")
1.2 价格清洗
# 去除货币符号
df["价格_num"] = df["价格"].str.replace(r"[¥¥$元]", "", regex=True)
df["价格_num"] = pd.to_numeric(df["价格_num"], errors="coerce")
print(df[["价格", "价格_num"]])
1.3 标签拆分
# 按逗号拆分标签
df["标签列表"] = df["标签"].str.split(",")
# 展开标签(每个标签一行)
tags_exploded = df[["标题", "标签"]].assign(
标签=df["标签"].str.split(",")
).explode("标签")
tags_exploded["标签"] = tags_exploded["标签"].str.strip()
# 统计标签频率
tag_counts = tags_exploded["标签"].value_counts()
print("标签频率:")
print(tag_counts)
二、正则表达式提取
2.1 extract(提取匹配)
df = pd.DataFrame({
"地址": ["北京市朝阳区xx路1号", "上海市浦东新区yy路2号", "广州市天河区zz路3号"],
"手机号": ["电话:13800138000", "联系方式:13912345678", "手机:15088887777"],
"规格": ["重量:1.5kg", "尺寸:30×20×10cm", "容量:500ml"],
})
# 提取城市
df["城市"] = df["地址"].str.extract(r"(北京|上海|广州|深圳)市?")
print(df["城市"])
# 提取手机号
df["手机"] = df["手机号"].str.extract(r"(1[3-9]\d{9})")
print(df["手机"])
# 提取数字+单位
df["数值"] = df["规格"].str.extract(r"([\d.]+)")
df["单位"] = df["规格"].str.extract(r"([a-zA-Z\u4e00-\u9fa5]+)$")
print(df[["规格", "数值", "单位"]])
2.2 extractall(提取所有匹配)
text = pd.Series(["Python3.8和Python3.9", "Java8和Java11"])
# 提取所有版本号
versions = text.str.extractall(r"(\w+)(\d+[\.\d]*)")
print(versions)
2.3 findall
# 找出所有邮箱
emails = pd.Series(["联系abc@qq.com或xyz@163.com", "无邮箱", "test@gmail.com"])
result = emails.str.findall(r"[\w.]+@[\w.]+")
print(result)
三、文本替换
df = pd.DataFrame({
"评论": ["这个产品很好!!!推荐", "一般般吧...", "太差了!!!退!!!"],
})
# 去除重复标点
df["评论_clean"] = df["评论"].str.replace(r"[!!]{2,}", "!", regex=True)
df["评论_clean"] = df["评论_clean"].str.replace(r"\.{2,}", "...", regex=True)
# 去除HTML标签
html_text = pd.Series(["<p>正文内容</p>", "<div class='x'>标题</div>"])
clean = html_text.str.replace(r"<[^>]+>", "", regex=True)
print(clean)
# 替换表情
df["评论_clean"] = df["评论"].str.replace(r"[^\u4e00-\u9fa5a-zA-Z0-9,。!?、]", "", regex=True)
四、关键词提取
4.1 词频统计
import jieba
df = pd.DataFrame({
"标题": [
"Python数据分析入门教程",
"Python爬虫实战项目",
"数据分析Pandas高级技巧",
"机器学习Python入门",
],
})
# 分词
df["分词"] = df["标题"].apply(lambda x: jieba.lcut(x))
# 统计词频
from collections import Counter
all_words = [w for words in df["分词"] for w in words if len(w) > 1]
word_counts = Counter(all_words)
print("高频词:")
for word, count in word_counts.most_common(10):
print(f" {word}: {count}")
4.2 停用词过滤
# 简易停用词表
stop_words = {"的", "了", "和", "是", "在", "与", "及", "等", "中", "为", "对", "从",
"到", "被", "把", "让", "用", "也", "就", "都", "而", "及", "等", "之"}
df["关键词"] = df["分词"].apply(
lambda words: [w for w in words if len(w) > 1 and w not in stop_words]
)
print(df[["标题", "关键词"]])
五、实战:评论数据清洗
import pandas as pd
import re
df = pd.DataFrame({
"评论": [
" 产品很好,推荐购买! ",
"一般般吧。。。不太满意",
"太差了!!!退!!!2026-04-01",
"<p>质量不错</p>",
"客服态度很差!!不推荐!!订单号:ORD123456",
None,
" ",
],
})
def clean_comment(text):
"""清洗评论文本"""
if pd.isna(text) or str(text).strip() == "":
return ""
text = str(text)
# 去HTML标签
text = re.sub(r"<[^>]+>", "", text)
# 去订单号等编号
text = re.sub(r"订单号[::]\s*\w+", "", text)
# 去日期
text = re.sub(r"\d{4}-\d{2}-\d{2}", "", text)
# 去重复标点
text = re.sub(r"([!?。,])\1+", r"\1", text)
text = re.sub(r"\.{2,}", "...", text)
# 去首尾空格
text = text.strip()
return text
df["清洗后"] = df["评论"].apply(clean_comment)
print(df[["评论", "清洗后"]])
六、知识卡
| 方法 | 说明 |
|---|---|
| .str.strip() | 去首尾空格 |
| .str.contains() | 包含检测 |
| .str.replace() | 正则替换 |
| .str.extract() | 正则提取(第一个) |
| .str.extractall() | 正则提取(所有) |
| .str.findall() | 找所有匹配 |
| .str.split() | 拆分字符串 |
| .explode() | 展开列表 |
| .str.len() | 字符串长度 |
| jieba.lcut() | 中文分词 |
| Counter | 词频统计 |
七、课后作业
必做题:
- 清洗价格字段(去符号、转数值)
- 用正则提取手机号和邮箱
- 对文本列做分词和词频统计
选做题:
- 编写完整的文本清洗函数
- 实现关键词提取与标签自动生成
有问题欢迎评论区留言,大家一起讨论!
标签:Python | Pandas | 文本处理 | 正则表达式 | 关键词提取 | 字符串清洗
更多推荐
所有评论(0)