第三讲 正则表达式库
一、正则表达式
正则表达式(regular expressio)表示了一组字符串的特征和模式,简洁,“一行胜千言”
正则表达式在文本处理中十分常用:
- 表达文本类型的特征(病毒、入侵等)
- 同时查找或替换一组字符串
- 匹配字符串的全部或部分
正则表达式的常用操作符:
操作符 | 说明 | 实例 |
---|---|---|
. | 表示任何单个字符 | |
[ ] | 字符集,对单个字符给出取值范围 | [abc]表示a、b、c,[a‐z]表示a到z单个字符 |
[^ ] | 非字符集,对单个字符给出排除范围 | [^abc]表示非a或b或c的单个字符 |
* | 前一个字符0次或无限次扩展 | abc* 表示 ab、abc、abcc、abccc等 |
+ | 前一个字符1次或无限次扩展 | abc+ 表示 abc、abcc、abccc |
? | 前一个字符0次或1次扩展 | abc? 表示 ab、abc |
左右表达式任意一个 | ||
{m} | 扩展前一个字符m次 | ab{2}c表示abbc |
{m,n} | 扩展前一个字符m至n次(含n) | ab{1,2}c表示abc、abbc |
^ | 匹配字符串开头 | ^abc表示abc且在一个字符串的开头 |
$ | 匹配字符串结尾 | abc$表示abc且在一个字符串结尾 |
( ) | 分组标记,内部只能使用 | 操作符 |
\d | 数字,等价于[0‐9] | |
\w | 单词字符,等价于[A‐Za‐z0‐9_] |
正则表达式实例:
1+$ | 由26个字母组成的字符串 |
---|---|
2+$ | 由26个字母和数字组成的字符串 |
^‐?\d+$ | 整数形式的字符串 |
3[1‐9][0‐9]$ | 正整数形式的字符串 |
[1‐9]\d{5} | 中国境内邮政编码,6位(开头不能是0) |
[\u4e00‐\u9fa5] | 匹配中文字符(在utf-8编码中的位置 |
\d{3}‐\d{8} | \d{4}‐\d{7} |
匹配IP地址的正则表达式(IP地址分为4段,每段是0-255):
分别匹配0-99,100-199,200-249,250-255
(([1‐9]?\d|1\d{2}|2[0‐4]\d|25[0‐5]).){3}([1‐9]?\d|1\d{2}|2[0‐4]\d|25[0‐5])
二、Re库的基本使用
在Re库中,正则表达式是原生字符串(raw string)类型
可以采用原生字符串类型表达正则表达式:r’\d{3}‐\d{8}|\d{4}‐\d{7}’
也可以用字符串类型,但要考虑转义符的影响:’\\d{3}‐\\d{8}|\\d{4}‐\\d{7}’
所有在含有转义符比较多的正则表达式中,尽量用原生字符串。
1.Re库6种主要功能函数
函数 | 说明 |
---|---|
re.search() | 在一个字符串中搜索匹配正则表达式的第一个位置,返回match对象 |
re.match() | 从一个字符串的开始位置起匹配正则表达式,返回match对象 |
re.findall() | 搜索字符串,以列表类型返回全部能匹配的子串 |
re.split() | 将一个字符串按照正则表达式匹配结果进行分割,返回列表类型 |
re.finditer() | 搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象 |
re.sub() | 在一个字符串中替换所有匹配正则表达式的子串,返回替换后的字符串 |
### 1 re.search(pattern, string, flags=0)
# pattern:正则表达式的字符串或者原生字符串表示
# string:待匹配字符串
# flags:正则表达式使用时的控制标记
>>>import re
>>>match = re.search(r'[1‐9]\d{5}','BIT 100081')
>>>if match:
print(match.group(0))
100081
### 2 re.match(pattern, string, flags=0)
>>>match = re.match(r'[1‐9]\d{5}','BIT 100081')
>>>if match:
print(match.group(0))
#没有输出,因为re.match从头开始匹配,match对象是空的
>>>match = re.match(r'[1‐9]\d{5}','100081 BIT')
>>>if match:
print(match.group(0))
100081
### 3 re.findall(pattern, string, flags=0)
>>>ls = re.findall(r'[1‐9]\d{5}','BIT100081 THU100084')
>>>ls
['100081', '100084']
### 4 re.split(pattern, string, maxsplit=0, flags=0)
# maxsplit:最大分割数,规定将原字符串最大分割成多少个部分,超过最大分割数的部分将作为一个整体
# 将一个字符串中与正则表达式相匹配的部分去掉,并作为分割点将剩下的字符串分割,存入列表
>>>re.split(r'[1‐9]\d{5}','BIT100081 THU100084')
['BIT', ' THU', '']
>>>re.split(r'[1‐9]\d{5}','BIT100081 THU100084',maxsplit=1)
['BIT', ' THU100084']
>>>re.split(r'[1‐9]\d{5}','BIT100081 THU100084 THU100084',maxsplit=1)
['BIT', ' THU100084 THU100084']
### 5 re.finditer(pattern, string, flags=0)
# 注意返回的是match对象的迭代类型,只能在 for 循环中使用
>>>for m in re.finditer(r'[1‐9]\d{5}','BIT100081 TSU100084'):
if m:
print(m.group(0))
100081
100084
### 6 re.sub(pattern,repl,string,count=0,flags=0)
# repl:替换后的字符串
# count:最大替换次数
>>>re.sub(r'[1‐9]\d{5}',':zipcode','BIT100081 TSU100084')
'BIT:zipcode TSU:zipcode'
- re.compile( pattern,flag=0 )可以将正则表达式的字符串形式编译成为正则表达式的类型pattern
- 对于对象regex六种函数依然能用
#面向对象的方法
#将正则表达式字符串表示r'[1‐9]\d{5}'真正地转化成正则表达式类型
>>>regex = re.compile(r'[1‐9]\d{5}')
>>>regex.search('BIT100081 TSU100084').group(0)#可以直接对对象regex进行操作
'100081'
2.Re库的match对象
match对象的四种属性:
属性 | 说明 |
---|---|
.string | 待匹配的文本 |
.re | 匹配时使用的patter对象(正则表达式) |
.pos | 正则表达式搜索文本的开始位置 |
.endpos | 正则表达式搜索文本的结束位置 |
match对象的四种方法:
方法 | 说明 |
---|---|
group(0) | 获得匹配后的字符串 |
.start() | 匹配字符串在原始字符串的开始位置 |
.end() | 匹配字符串在原始字符串的结束位置 |
.span() | 返回(.start(), .end()),起始和终止位置 |
3.Re的贪婪匹配与最小匹配
在默认情况下,re库会采用贪婪匹配原则,即返回符合要求的最长字符串
例如:re.search(r’PY.*N’,’PYANBNCNDN’)
会返回最长的’PYANBNCNDN’
有时候需要输出最短的子串(最小匹配):
操作符 | 说明 |
---|---|
*? | 前一个字符0次或无限次扩展,最小匹配 |
+? | 前一个字符1次或无限次扩展,最小匹配 |
?? | 前一个字符0次或1次扩展,最小匹配 |
{m,n}? | 扩展前一个字符m至n次(含n),最小匹配 |
三、实例:淘宝信息定向爬虫
#CrowTaobaoPrice.py
import requests
import re
#获取页面
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
#解析页面 ilt记录信息
def parsePage(ilt, html):
try:
plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price = eval(plt[i].split(':')[1])
title = eval(tlt[i].split(':')[1])
ilt.append([price , title])
except:
print("")
#打印商品信息
def printGoodsList(ilt):
tplt = "{:4}\t{:8}\t{:16}"
print(tplt.format("序号", "价格", "商品名称"))
count = 0
for g in ilt:
count = count + 1
print(tplt.format(count, g[0], g[1]))
def main():
goods = '书包'
depth = 3
start_url = 'https://s.taobao.com/search?q=' + goods
infoList = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44*i)
html = getHTMLText(url)
parsePage(infoList, html)
except:
continue
printGoodsList(infoList)
main()
四、股票数据定向爬虫
#CrawBaiduStocksA.py
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def getStockList(lst, stockURL):
html = getHTMLText(stockURL)
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
except:
continue
def getStockInfo(lst, stockURL, fpath):
for stock in lst:
url = stockURL + stock + ".html"
html = getHTMLText(url)
try:
if html=="":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div',attrs={'class':'stock-bets'})
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称': name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val
with open(fpath, 'a', encoding='utf-8') as f:
f.write( str(infoDict) + '\n' )
except:
traceback.print_exc()
continue
def main():
stock_list_url = 'https://quote.eastmoney.com/stocklist.html'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'D:/BaiduStockInfo.txt'
slist=[]
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
main()
对代码进行改进,显示进度条:
#CrawBaiduStocksB.py
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url, code="utf-8"):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = code
return r.text
except:
return ""
def getStockList(lst, stockURL):
html = getHTMLText(stockURL, "GB2312")
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
except:
continue
def getStockInfo(lst, stockURL, fpath):
count = 0
for stock in lst:
url = stockURL + stock + ".html"
html = getHTMLText(url)
try:
if html=="":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div',attrs={'class':'stock-bets'})
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称': name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val
with open(fpath, 'a', encoding='utf-8') as f:
f.write( str(infoDict) + '\n' )
count = count + 1
print("\r当前进度: {:.2f}%".format(count*100/len(lst)),end="")
except:
count = count + 1
print("\r当前进度: {:.2f}%".format(count*100/len(lst)),end="")
continue
def main():
stock_list_url = 'https://quote.eastmoney.com/stocklist.html'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'D:/BaiduStockInfo.txt'
slist=[]
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
main()