一、正則使用
正則表達式常用匹配規則:
匹配某個字符串:
text = 'hello'
ret = re.match('he',text)
print(ret.group())
>> he
以上便可以在hello
中,匹配出he
。
點(.)匹配任意的字符:
text = "ab"
ret = re.match('.',text)
print(ret.group())
>> a
但是點(.)不能匹配不到換行符。示例代碼如下:
text = "ab"
ret = re.match('.',text)
print(ret.group())
>> AttributeError: 'NoneType' object has no attribute 'group'
\d匹配任意的數字:
text = "123"
ret = re.match('\d',text)
print(ret.group())
>> 1
\D匹配任意的非數字:
text = "a"
ret = re.match('\D',text)
print(ret.group())
>> a
而如果text是等於一個數字,那麼就匹配不成功了。示例代碼如下:
text = "1"
ret = re.match('\D',text)
print(ret.group())
>> AttributeError: 'NoneType' object has no attribute 'group'
\s匹配的是空白字符(包括:\n,\t,\r和空格):
text = "\t"
ret = re.match('\s',text)
print(ret.group())
>> 空白
\w匹配的是a-z
和A-Z
以及數字和下劃線:
text = "_"
ret = re.match('\w',text)
print(ret.group())
>> _
而如果要匹配一個其他的字符,那麼就匹配不到。示例代碼如下:
text = "+"
ret = re.match('\w',text)
print(ret.group())
>> AttributeError: 'NoneType' object has no attribute
\W匹配的是和\w相反的:
text = "+"
ret = re.match('\W',text)
print(ret.group())
>> +
而如果你的text是一個下劃線或者英文字符,那麼就匹配不到了。示例代碼如下:
text = "_"
ret = re.match('\W',text)
print(ret.group())
>> AttributeError: 'NoneType' object has no attribute
[]組合的方式,只要滿足中括號中的某一項都算匹配成功:
text = "0731-88888888"
ret = re.match('[\d\-]+',text)
print(ret.group())
>> 0731-88888888
之前的幾種匹配規則,可以使用中括號的形式來進行替代:
- \d:[0-9]
- \D:0-9
- \w:[0-9a-zA-Z_]
- \W:[^0-9a-zA-Z_]
匹配多個字符:
-
*
:可以匹配0或者任意多個字符。示例代碼如下:text = "0731" ret = re.match('\d*',text) print(ret.group()) >> 0731
以上因爲匹配的要求是
\d
,那麼就要求是數字,後面跟了一個星號,就可以匹配到0731這四個字符。 -
+
:可以匹配1個或者多個字符。最少一個。示例代碼如下:text = "abc" ret = re.match('\w+',text) print(ret.group()) >> abc
因爲匹配的是
\w
,那麼就要求是英文字符,後面跟了一個加號,意味着最少要有一個滿足\w
的字符才能夠匹配到。如果text是一個空白字符或者是一個不滿足\w的字符,那麼就會報錯。示例代碼如下:text = "" ret = re.match('\w+',text) print(ret.group()) >> AttributeError: 'NoneType' object has no attribute
-
?
:匹配的字符可以出現一次或者不出現(0或者1)。示例代碼如下:text = "123" ret = re.match('\d?',text) print(ret.group()) >> 1
-
{m}
:匹配m個字符。示例代碼如下:text = "123" ret = re.match('\d{2}',text) print(ret.group()) >> 12
-
{m,n}
:匹配m-n個字符。在這中間的字符都可以匹配到。示例代碼如下:text = "123" ret = re.match('\d{1,2}',text) prit(ret.group()) >> 12
如果text只有一個字符,那麼也可以匹配出來。示例代碼如下:
text = "1" ret = re.match('\d{1,2}',text) prit(ret.group()) >> 1
^(脫字號):以...開始:
text = "hello"
ret = re.match('^h',text)
print(ret.group())
如果是在中括號中,那麼代表的是取反操作.
$:以...結束:
# 匹配163.com的郵箱
text = "[email protected]"
ret = re.search('\w+@163\.com$',text)
print(ret.group())
>> [email protected]
|:匹配多個表達式或者字符串:
text = "hello|world"
ret = re.search('hello',text)
print(ret.group())
>> hello
貪婪模式和非貪婪模式:
貪婪模式:正則表達式會匹配儘量多的字符。默認是貪婪模式。
非貪婪模式:正則表達式會盡量少的匹配字符。
示例代碼如下:
text = "0123456"
ret = re.match('\d+',text)
print(ret.group())
# 因爲默認採用貪婪模式,所以會輸出0123456
>> 0123456
可以改成非貪婪模式,那麼就只會匹配到0。示例代碼如下:
text = "0123456"
ret = re.match('\d+?',text)
print(ret.group())
案例:匹配0-100
之間的數字:
text = '99'
ret = re.match('[1-9]?\d$|100$',text)
print(ret.group())
>> 99
而如果text=101
,那麼就會拋出一個異常。示例代碼如下:
text = '101'
ret = re.match('[1-9]?\d$|100$',text)
print(ret.group())
>> AttributeError: 'NoneType' object has no attribute 'group'
轉義字符和原生字符串:
在正則表達式中,有些字符是有特殊意義的字符。因此如果想要匹配這些字符,那麼就必須使用反斜槓進行轉義。比如$
代表的是以...結尾,如果想要匹配$
,那麼就必須使用\$
。示例代碼如下:
text = "apple price is \$99,orange paice is $88"
ret = re.search('\$(\d+)',text)
print(ret.group())
>> $99
原生字符串:
在正則表達式中,\
是專門用來做轉義的。在Python中\
也是用來做轉義的。因此如果想要在普通的字符串中匹配出\
,那麼要給出四個\
。示例代碼如下:
text = "apple \c"
ret = re.search('\\\\c',text)
print(ret.group())
因此要使用原生字符串就可以解決這個問題:
text = "apple \c"
ret = re.search(r'\\c',text)
print(ret.group())
re模塊中常用函數:
match:
從開始的位置進行匹配。如果開始的位置沒有匹配到。就直接失敗了。示例代碼如下:
text = 'hello'
ret = re.match('h',text)
print(ret.group())
>> h
如果第一個字母不是h
,那麼就會失敗。示例代碼如下:
text = 'ahello'
ret = re.match('h',text)
print(ret.group())
>> AttributeError: 'NoneType' object has no attribute 'group'
如果想要匹配換行的數據,那麼就要傳入一個flag=re.DOTALL
,就可以匹配換行符了。示例代碼如下:
text = "abc\nabc"
ret = re.match('abc.*abc',text,re.DOTALL)
print(ret.group())
search:
在字符串中找滿足條件的字符。如果找到,就返回。說白了,就是隻會找到第一個滿足條件的。
text = 'apple price $99 orange price $88'
ret = re.search('\d+',text)
print(ret.group())
>> 99
分組:
在正則表達式中,可以對過濾到的字符串進行分組。分組使用圓括號的方式。
group
:和group(0)
是等價的,返回的是整個滿足條件的字符串。groups
:返回的是裏面的子組。索引從1開始。group(1)
:返回的是第一個子組,可以傳入多個。
示例代碼如下:
text = "apple price is $99,orange price is $10"
ret = re.search(r".*(\$\d+).*(\$\d+)",text)
print(ret.group())
print(ret.group(0))
print(ret.group(1))
print(ret.group(2))
print(ret.groups())
findall:
找出所有滿足條件的,返回的是一個列表。
text = 'apple price $99 orange price $88'
ret = re.findall('\d+',text)
print(ret)
>> ['99', '88']
sub:
用來替換字符串。將匹配到的字符串替換爲其他字符串。
text = 'apple price $99 orange price $88'
ret = re.sub('\d+','0',text)
print(ret)
>> apple price $0 orange price $0
split:
使用正則表達式來分割字符串。
text = "hello world ni hao"
ret = re.split('\W',text)
print(ret)
>> ["hello","world","ni","hao"]
compile:
對於一些經常要用到的正則表達式,可以使用compile
進行編譯,後期再使用的時候可以直接拿過來用,執行效率會更快。而且compile
還可以指定flag=re.VERBOSE
,在寫正則表達式的時候可以做好註釋。示例代碼如下:
text = "the number is 20.50"
r = re.compile(r"""
\d+ # 小數點前面的數字
\.? # 小數點
\d* # 小數點後面的數字
""",re.VERBOSE)
ret = re.search(r,text)
print(ret.group())
二、爬取古詩詞網
__author__ = '田明博'
__date__ = '2019/10/11 12:56'
import re
import requests
def get_page(link):
url = link
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0',
}
resp = requests.get(url, headers=headers)
text = resp.text
# 獲取題目
titles = re.findall(r'<div\sclass="cont">.*?<b>(.*?)</b>', text, re.DOTALL) # re.DOTALL: . 匹配所有字符
source = re.findall(r'<p class="source">.*?<a.*?>(.*?)</a>', text, re.DOTALL) # 獲取朝代
authors = re.findall(r'<p class="source">.*?<a.*?><a.*?>(.*?)</a>', text, re.DOTALL) # 獲取作者
poems_all = re.findall(r'<div class="contson".*?>(.*?)</div>', text, re.DOTALL) # 後獲取所有古詩內容
contents = []
for poems in poems_all:
poems = re.sub(r'<.*?>|\n', "", poems) #去除\n<br>
contents.append(poems.strip())
# print(titles, source, authors, contents)
'''
all_poems = []
for x in range(len(titles)):
one_poem = {}
one_poem['題目'] = titles[x]
one_poem['朝代'] = source[x]
one_poem['作者'] = authors[x]
one_poem['內容'] = contents[x]
all_poems.append(one_poem)
print(all_poems)
'''
# 功能同上
all_poems = []
for value in zip(titles, source, authors, contents):
title, source, author, content = value # 元組解包
one_poem = {}
one_poem['題目'] = title
one_poem['朝代'] = source
one_poem['作者'] = author
one_poem['內容'] = content
all_poems.append(one_poem)
print(all_poems)
def main():
num = int(input('輸入爬取頁數'))
for i in range(num):
link = 'https://www.gushiwen.org/default_{}.aspx'.format(num)
get_page(link)
if __name__ == '__main__':
main()
運行截圖: