代码详解之什么是Python正则表达式

本文介绍如何使用Python的正则表达式模块简化文本数据处理任务,通过实例演示了如何快速查找特定格式的内容,如电子邮件和电话号码,以及如何统计标点符号数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

处理文本数据的一个主要任务就是创建许多以文本为基础的特性。

人们可能想要在文本中找出特定格式的内容,比如找出存在于文本中的电子邮件,或者大型文本中的电话号码。
在这里插入图片描述

虽然想要实现上述功能听起来很繁琐,但是如果使用Python正则表达式模块,就可以使这一操作更加简单。

假设要在一篇特定的文章中找出标点符号的数量。以狄更斯的作品文本为例。

你通常会怎么做?

最简单的方法如下:

target = [';','.',',','–'] 
string = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only." 
num _ points = 0 
num_puncts = 0 
for punct in target: 
 if punct in string: 
 num_puncts+=string.count(punct)print(num_puncts) 
------------------------------------------------------------------ 
19 

如果没有可支配的re模块,那就要用到上面的代码。但如果有re模块,则只需两行代码:

import re 
pattern = r"[;.,–]" 
print(len(re.findall(pattern,string))) 
------------------------------------------------------------------ 
19 

那,什么是正则表达式?

简而言之,正则表达式(regex)用于探索给定字符串中的固定模式。

我们想找到的模式可以是任何东西。

可以创建类似于查找电子邮件或手机号码的模式。还可以创建查找以a开头、以z结尾的字符串的模式。

在上面的例子中:

import re 
pattern = r'[,;.,–]' 
print(len(re.findall(pattern,string))) 

我们想找出的模式是 r’[,;.,–]’。这个模式可找出想要的4个字符中的任何一个。regex101是一个用于测试模式的工具。将模式应用到目标字符串时,呈现出以下界面。

在这里插入图片描述
如图所示,可以在目标字符串中根据需要找到,;.,–。

每当需要测试正则表达式时,都会用到上面的工具。这比一次又一次运行python要快得多,调试也容易得多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值