【Python学习笔记】Coursera课程《Using Python to Access Web Data 》 密歇根大学 Charles Severance——Week2 Regular Expressions课堂笔记
Coursera课程《Using Python to Access Web Data》 密歇根大学 Charles Severance
**Week2 Regular Expressions **
11.1 Regular Expressions
11.1.1 Python Regular Expression Quick Guide
| ^ | 匹配一行的开头 |
|---|---|
| $ | 匹配一行的末尾 |
| . | 匹配任何字符 |
| \s | 匹配空白字符 |
| \S | 匹配任何非空白字符 |
| ***** | 重复一个字符0次或多次 |
| *? | 重复一个字符0次或多次(non-greedy) |
| + | 重复一个字符一次或多次 |
| +? | 重复一个字符一次或多次(non-greedy) |
| [aeiou] | 匹配被列出来的一个单字符 |
| [^XYZ] | 匹配没有被列出来的一个单字符 |
| [a-z0-9] | 设置可以包含的字符 |
| () | 表示提取字符串的开头处 |
| ) | 表示提取字符串的结尾处 |
【注】non-greedy模式表示尽可能少的匹配字符
11.1.2 The Regular Expression Module
在程序里使用正则表达式之前,必须使用'import re'引入一个模块。
然后可以使用re.search()来查看,是否一个字符串匹配正则表达式,和find()有点相似。
也可以使用re.findall()来提取一个字符串的部分来匹配正则表达式,这和find()与切片var[5:10]很相似。
11.1.3 Using re.search() Like find()
使用find()的代码
hand = open('mobox-short.txt')
for line in hand:
line = line.restrip()
if line.find('From:') >= 0:
print(line)
使用re.search()的代码
import re
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if re.search('From:', line):
print(line)
11.1.4 Using re.search() Like startswith()
使用startswith()的代码
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if line.startswith('From:'):
print(line)
使用re.search()的代码
import re
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if re.search('From:', line):
print(line)
11.1.5 Wild-Card Characters
点号可以匹配任何字符。但如果加上了星号,那么这个字符可以出现任何次。
所以正则表达式^X.*:表示,查找以X开头的字符串,X后面可以接任何字符,而且任意长度。
那么例如我们可能会返回这样的
X-Sieve: CMU Sieve 2.3
X-DSPAM-Result: Innocent
X-Plane is behind schedule: two weeks
11.1.6 Fine-Tuning Your Match
为了更精准地匹配到我们想要的东西。我们可以稍作改进。
比如改成^X-\S+:表示,查找以X开头的字符串,X后面可以接任何不含空格的字符,而且字符数大于等于1个。
那么我们会上面的两行数据,而不会返回第三行。
11.2 Extracting Data
使用[0-9]+,表示查找一个或多个数字。
>>> import re
>>> x = 'My 2 favorite numbers are 19 and 42'
>>> y = re.findall('[0-9]+', x)
>>> print(y)
['2', '19', '42']
11.2.1 Warning: Greedy Matching
之前说的Greedy模式,其实就是匹配符合条件的最长的字符。
比如说
>>> import re
>>> x = 'From: Using the : character'
>>> y = re.findall('^F.+:', x)
>>> print(y)
['From: Using the :']
因为是Greedy模式,所以不是匹配的'From:'。
11.2.2 Non-Greedy Matching
而如果在+或后加上一个?,则可以切换到Non-Greedy*模式。
>>> import re
>>> x = 'From: Using the : character'
>>> y = re.findall('^F.+?:', x)
>>> print(y)
['From:']
11.2.3 Fine-Tuning String Extraction
如果我们要定位下面这段中的邮件地址。
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
那么我们可以这样
>>> y = re.findall('\S+@\S+', x)
>>> print(y)
['stephen.marquard@uct.ac.za']
使用括号,我们可以规定我们想要提取的文本的起始。比如这样
>>> y = re.findall('From (\S+@\S+)', x)
>>> print(y)
['stephen.marquard@uct.ac.za']
11.2.4 Spam Confidence
一个例子。
import re
hand = open('mbox-short.txt')
numlist = list()
for line in hand:
line = line.rstrip()
stuff = re.findall('X-DSPAM-Confidence: ([0-9.]+)', line)
if len(stuff) != 1: continue
num = float(stuff[0])
numlist.append(num)
print('Maximum:', max(numlist))
Assignment
import re
hand = open('actual.txt')
numlist = list()
counts = dict()
for line in hand:
line = line.rstrip()
stuff = re.findall('[0-9]+', line)
if len(stuff) == 0: continue
for i in range(len(stuff)):
num = int(stuff[i])
numlist.append(num)
print(len(numlist))
print(sum(numlist))
【Python学习笔记】Coursera课程《Using Python to Access Web Data 》 密歇根大学 Charles Severance——Week2 Regular Expressions课堂笔记的更多相关文章
- 【Python学习笔记】Coursera课程《Python Data Structures》 密歇根大学 Charles Severance——Week6 Tuple课堂笔记
Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week6 Tuple 10 Tuples 10.1 Tuples A ...
- 【Python学习笔记】Coursera课程《Using Python to Access Web Data》 密歇根大学 Charles Severance——Week6 JSON and the REST Architecture课堂笔记
Coursera课程<Using Python to Access Web Data> 密歇根大学 Week6 JSON and the REST Architecture 13.5 Ja ...
- 【Python学习笔记】Coursera课程《Using Databases with Python》 密歇根大学 Charles Severance——Week4 Many-to-Many Relationships in SQL课堂笔记
Coursera课程<Using Databases with Python> 密歇根大学 Week4 Many-to-Many Relationships in SQL 15.8 Man ...
- Coursera课程《Python数据结构》中课程目录
Python Data Structures Python Data Structures is the second course in the specialization Python for ...
- 《Using Python to Access Web Data》Week4 Programs that Surf the Web 课堂笔记
Coursera课程<Using Python to Access Web Data> 密歇根大学 Week4 Programs that Surf the Web 12.3 Unicod ...
- 《Using Python to Access Web Data》 Week5 Web Services and XML 课堂笔记
Coursera课程<Using Python to Access Web Data> 密歇根大学 Week5 Web Services and XML 13.1 Data on the ...
- 《Using Python to Access Web Data》 Week3 Networks and Sockets 课堂笔记
Coursera课程<Using Python to Access Web Data> 密歇根大学 Week3 Networks and Sockets 12.1 Networked Te ...
- Python学习入门基础教程(learning Python)--5.6 Python读文件操作高级
前文5.2节和5.4节分别就Python下读文件操作做了基础性讲述和提升性介绍,但是仍有些问题,比如在5.4节里涉及到一个多次读文件的问题,实际上我们还没有完全阐述完毕,下面这个图片的问题在哪呢? 问 ...
- Python学习系列(四)Python 入门语法规则2
Python学习系列(四)Python 入门语法规则2 2017-4-3 09:18:04 编码和解码 Unicode.gbk,utf8之间的关系 2.对于py2.7, 如果utf8>gbk, ...
随机推荐
- Ajax在jQuery中的应用(加载异步数据、请求服务器数据)
加载异步数据 jQuery中的load()方法 load(url,[data],[callback]) url:被加载的页面地址 [data]:可选项表示发送到服务器的数据,其格式为 key/valu ...
- 【python】windows7下怎样安装whl
windows7 python2.7 1.用管理员方式打开cmd 2.首先通过pip命令安装wheel 如果提示’pip’不是内部或外部命令,也不是可运行的程序或批处理文件 ①将python安装目录下 ...
- BZOJ4247 挂饰(动态规划)
相当于一个有负体积的背包.显然如果确定了选哪些,应该先把体积小的挂上去.于是按体积从小到大排序,就是一个裸的背包了. #include<iostream> #include<cstd ...
- Python_css选择器
1. 概述 css是英文Cascading Style Sheets的缩写,称为层叠样式表,用于对页面进行美化. 存在方式有三种:元素内联.页面嵌入和外部引入,比较三种方式的优缺点. 语法:style ...
- [CF1083C]Max Mex
题目大意:有一棵$n(n\leqslant2\times10^5)$个点的树,每个点有点权,所有的点权构成了$0\sim n-1$的排列.$q(q\leqslant2\times10^5)$次操作,操 ...
- [九省联考2018]IIIDX 贪心 线段树
~~~题面~~~ 题解: 一开始翻网上题解看了好久都没看懂,感觉很多人都讲得不太详细,所以导致一些细节的地方看不懂,所以这里就写详细一点吧,如果有不对的or不懂的可以发评论在下面. 首先有一个比较明显 ...
- BZOJ4754 & 洛谷4323 & LOJ2072:[JSOI2016]独特的树叶——题解
https://www.lydsy.com/JudgeOnline/problem.php?id=4754 https://www.luogu.org/problemnew/show/P4323 ht ...
- 洛谷1578:[WC2002]奶牛浴场——题解
https://www.luogu.org/problemnew/show/P1578#sub 由于John建造了牛场围栏,激起了奶牛的愤怒,奶牛的产奶量急剧减少.为了讨好奶牛,John决定在牛场中建 ...
- POI 2018.10.27
[POI2015]LOG 维护一个长度为n的序列,一开始都是0,支持以下两种操作:1.U k a 将序列中第k个数修改为a.2.Z c s 在这个序列上,每次选出c个正数,并将它们都减去1,询问能否进 ...
- POSIX.2 正则表达式
By francis_hao Oct 1,2017 这里的正则表达式主要是指扩展正则,也就是egrep(grep -e)用到的正则表达式. 字符 含义 类别说明 | 分割分支,正则表达式会去 ...