加入收藏 | 设为首页 | 会员中心 | 我要投稿 莆田站长网 (https://www.0594zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

代码详解:Python正则表达式的优秀使用指南

发布时间:2019-09-29 22:53:58 所属栏目:优化 来源:读芯术
导读:副标题#e# 处理文本数据的一个主要任务就是创建许多以文本为基础的特性。 人们可能想要在文本中找出特定格式的内容,比如找出存在于文本中的电子邮件,或者大型文本中的电话号码。 虽然想要实现上述功能听起来很繁琐,但是如果使用Python正则表达式模块,就
副标题[/!--empirenews.page--]

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

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

代码详解:Python正则表达式的优秀使用指南

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

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

你通常会怎么做?

最简单的方法如下:

  1. target = [';','.',',','–'] 
  2. 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." 
  3. num _ points = 0 
  4. num_puncts = 0 
  5. for punct in target: 
  6.  if punct in string: 
  7.  num_puncts+=string.count(punct)print(num_puncts) 
  8. ------------------------------------------------------------------ 
  9. 19 

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

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

本文讨论的是最常用的正则表达式模式,以及一些经常使用的正则表达式函数。

什么是正则表达式?

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

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

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

在上面的例子中:

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

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

代码详解:Python正则表达式的优秀使用指南

如图所示,可以在目标字符串中根据需要找到,;.,–。

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

现在我们已经可以在目标字符串中找到这些模式,那么如何真正创建这些模式呢?

创建模式

使用正则表达式时,首先需要学习的是如何创建模式。

接下来将对一些最常用的模式进行逐一介绍。

可以想到最简单的模式是一个简单的字符串。

  1. pattern = r'times' 
  2. string = "It was the best of times, it was the worst of times." 
  3. print(len(re.findall(pattern,string))) 

但这并不是很有用。为了帮助创建复杂的模式,正则表达式提供了特殊的字符/操作符。下面来逐个看看这些操作符。请等待gif加载。

1.[]操作符

这在第一个例子中使用过,可用于找到符合这些方括号中条件的一个字符。

[abc]-将查找文本中出现的所有a、b或c

[a-z]-将查找文本中出现的所有从a到z的字母

[a-z0–9A-Z]-将查找文本中出现的所有从A到Z的大写字母、从a到z的小写字母和从0到9的数字。

代码详解:Python正则表达式的优秀使用指南

可以很容易地在Python中运行下列代码:

  1. pattern = r'[a-zA-Z]' 
  2. string = "It was the best of times, it was the worst of times." 
  3. print(len(re.findall(pattern,string))) 

除了.findall,正则表达式还有很多其他功能,稍后会涉及到。

2.点算符

点运算符(.) 用于匹配除换行符以外的任何字符。

运算符最大的优点是,它们可以结合使用。

(编辑:莆田站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读