爬虫之re数据清洗

文章目录

  • 一、正则【Regular】
  • 二、重要语法
    • [1、获取内容: 左边(.*?)右边](#1、获取内容: 左边(.*?)右边)
    • [2、替换数据: re.sub('源数据|源数据', '目标数据', 字符串)](#2、替换数据: re.sub('源数据|源数据', '目标数据', 字符串))

一、正则【Regular】

概念: 根据程序员的指示, 从<字符串>中提取数据

结果: 列表

使用频率: 正则跟xpath相比, 正则是弟弟

二、重要语法

1、获取内容: 左边(.*?)右边

代码示例如下:

python 复制代码
import re
data = 'name: 张三; age: 18岁; addr: 北京; height: 180cm'
result = re.findall('; age: (.*?); ', data)
print(result)

运行结果如下:

python 复制代码
['18岁']

注意:re.findall()方法返回结果是列表

2、替换数据: re.sub('源数据|源数据', '目标数据', 字符串)

代码示例如下:

python 复制代码
import re
data = 'python  真 的 \t \n 非常 & * P  好用'
result = re.sub('\t|\n| |&|\*|P', '', data)
print(result)

运行结果如下:

python 复制代码
python真的非常好用
相关推荐
cup1111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0013 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵15 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf15 小时前
Agent 流程编排
后端·python·agent
copyer_xyf16 小时前
Agent RAG
后端·python·agent
copyer_xyf16 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf16 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏