正则表达式数据提取
Python数据分析入门Python
问题
如何用正则表达式提取文本中的信息?
答题要点
import re
import pandas as pd
# 基础匹配
text = "联系方式:13912345678,邮箱:user@example.com"
# 提取手机号
phone = re.search(r'1[3-9]\d{9}', text)
if phone:
print(f"手机号: {phone.group()}")
# 提取邮箱
email = re.search(r'[\w\.-]+@[\w\.-]+\.\w+', text)
if email:
print(f"邮箱: {email.group()}")
# 提取所有匹配
text_multi = "用户ID: 1001, 1002, 1003"
user_ids = re.findall(r'\d+', text_multi)
print(f"用户ID列表: {user_ids}")
# DataFrame中应用正则
df = pd.DataFrame({
'comment': [
'价格太贵了,要1999元',
'很便宜,只要99.9元',
'免费的,0元购'
]
})
# 提取价格数字
df['price'] = df['comment'].str.extract(r'(\d+\.?\d*)元')
print(df)
# 验证格式
df['has_phone'] = df['text'].str.contains(r'1[3-9]\d{9}')
# 替换
df['clean_text'] = df['text'].str.replace(r'[^\w\s]', '', regex=True) # 去除标点
# 分组捕获
text = "订单号:OD20240101001,金额:1299.00元"
match = re.search(r'订单号:(\w+),金额:([\d.]+)元', text)
if match:
order_id = match.group(1)
amount = match.group(2)
print(f"订单: {order_id}, 金额: {amount}")
# 常用正则模式
patterns = {
'手机号': r'1[3-9]\d{9}',
'邮箱': r'[\w\.-]+@[\w\.-]+\.\w+',
'身份证': r'\d{17}[\dXx]',
'网址': r'https?://[\w\-\.]+',
'日期': r'\d{4}-\d{2}-\d{2}',
'金额': r'\d+\.?\d*元',
'中文': r'[\u4e00-\u9fa5]+',
'IP地址': r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
}
# 提取UTM参数
url = "https://example.com?utm_source=wechat&utm_medium=feed&utm_campaign=spring"
params = re.findall(r'utm_(\w+)=(\w+)', url)
utm_dict = dict(params)
print(utm_dict) # {'source': 'wechat', 'medium': 'feed', ...}
# 批量提取
df['utm_source'] = df['url'].str.extract(r'utm_source=(\w+)')
df['utm_medium'] = df['url'].str.extract(r'utm_medium=(\w+)')
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题