正則表達式庫的使用


正則表達式的概念Regular Expression RE
優勢:簡潔 一行勝千言
用於對字符串的匹配
在文本處理中十分常用 
表達文本類型的特征(病毒,入侵檢測)
同時查找或替換一組字符串
匹配字符串的局部和全部
正則表達式的使用
首先將符合正則表達式語法的字符串轉化成正則表達式 特征
p = re.compile(regx)


操作符 說明 實例
. 表示任何單個字符
[ ] 字符集,對單個字符給出取值范圍 [abc]表示a、b、c,[a-z]表示所有的小寫字母
[^]
[^abc]表示非a或b或c的單個字符
* 前一個字符0次或無限次擴展 abc*表示ab,abc,abcc,abccc等
+ 前一個字符1次或無限次擴展 abc+表示abc,abcc,abccc等
? 前一個字符0次或1次擴展 abc?表示ab,abc
| 左右表達式任意一個 abc|def表示abc或def
{m} 擴展前一個字符m次 ab{2}c表示abbc
{m,n} 擴展前一個字符m至n次(含n) ab{1,2}c表示abc,abbc
^ 匹配字符串開頭 ^abc表示abc在一個字符串的開頭
$ 匹配字符串結尾 abc$表示abc在一個字符串的結尾
() 分組標識,內部只能使用|操作符 (abc)表示abc,(abc|def)表示abc,def
\d 數字,等價於[0-9]
\w 單詞字符等價於[A-Za-z0-9_]


^[A-Za-z]+$ 由26個字母組成的字符串
^[A-Za-z0-9]+$ 由26個字母和數字組成的字符串
^-?\d+$ 數據形式的字符串
^[0-9]*[1-9][0-9]*$ 正整數形式的字符串
[1-9]\d{5} 中國境內的郵政編碼
[\u4e00-\u9fa5] 匹配中文字符
\d{3}-\d{8}|\d{4}-\d{7} 國內電話號碼
(([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]) IP地址
Re庫是python的標准庫
import re
re庫采用raw string類型表示正則表達式,表示為
r'text'
如: r'[1-9]\d{5} '
r'\d{3}-\d{8}|\d{4}-\d{7}'
raw string是不包括對轉義字符再次轉義的字符串,建議使用raw string
Re庫的主要功能函數


函數 說明
re.search(pattern,string,flags=0) 在一個字符串中匹配正則表達式的第一個位置,返回match對象
re.match(pattern,string,flags=0) 從一個字符串的開始位置起匹配正則表達式,返回match對象
re.findall(pattern,string,flags=0) 搜索字符串,以列表類型返回全部能匹配的子串
re.split(pattern,string,maxsplit=0,flags=0) 將一個字符串按照正則表達式匹配結果進行侵害,返回列表類型, maxsplit表示最大分割數,剩余部分作為最后一個元素輸出
re.finditer(pattern,string,flags=0) 搜索字符串,返回一個匹配結果的迭代類型,每個迭代元素是match對象
re.sub(pattern,repl,string,count=0,flags = 0) 在一個字符串中替換所有匹配正則表達式的子串,返回替換后的字符串,repl為替換匹配字符串的字符串,count為最大替換次數
re.compile(pattern,flags = 0) 將正則表達式的字符串形式編譯所正則表達式對象
flags 說明
re.I re.IGONRECASE 忽略正則表達式的大小寫,[A-Z]能匹配小寫字符
re.M re.MULTILINE 正則表達式的中的^操作符能夠將給定字符串的每行當作匹配開始位置
re.S re.DOTALL 正則表達式的中的.操作符能夠匹配所有字符,默認匹配除換行外的所有字符
re庫的另一種等價用法
函數式用法,一次性操作
           rst = re.search(r'[1-9]\d{5}','BIT 10081')
面向對象用法,編譯后多次操作
pat = re.compile(r' [1-9]\d{5}')
rst = pat.search('BIT 10081')

Match對象 是一次匹配的結果,包含匹配的很多信息

Match對象的屬性
屬性 說明
.string 待匹配的文本
.re 匹配進使用pattern對象(正則表達式)
.pos 正則表達式搜索文本的開始位置
.endpos 正則表達式搜索文本的結束位置


方法 說明
.group(0) 獲得匹配的字符串
.start() 匹配字符串在原始字符串的開始位置
.end() 匹配字符串在原始字符串的結束位置
.span() 返回(.start(),.end())
Re庫的貪婪匹配和最小匹配
貪婪匹配:re庫默認采用貪婪匹配,即輸出匹配最長的子串
如:
  最小匹配:如何輸出最短的子串


操作符 說明
*? 前一個字符0次或無限次擴展,最小匹配
+? 前一個字符1次或無限次擴展,最小匹配
?? 前一個字符0次或1次擴展,最小匹配
{m,n}? 前一個字符m至n次(含n),最小匹配
只要長度輸出可能不同,都可以通過在操作符后增加?變成最小匹配
實例1:淘寶比價爬蟲
    
    
    
            
  1. #CrowTaobaoPrice.py
  2. import requests
  3. import re
  4. def getHTMLText(url):
  5. try:
  6. r = requests.get(url, timeout=30)
  7. r.raise_for_status()
  8. r.encoding = r.apparent_encoding
  9. return r.text
  10. except:
  11. return ""
  12. def parsePage(ilt, html):
  13. try:
  14. plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
  15. tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
  16. for i in range(len(plt)):
  17. price = eval(plt[i].split(':')[1])
  18. title = eval(tlt[i].split(':')[1])
  19. ilt.append([price , title])
  20. except:
  21. print("")
  22. def printGoodsList(ilt):
  23. tplt = "{:4}\t{:8}\t{:16}"
  24. print(tplt.format("序號", "價格", "商品名稱"))
  25. count = 0
  26. for g in ilt:
  27. count = count + 1
  28. print(tplt.format(count, g[0], g[1]))
  29. def main():
  30. goods = '書包'
  31. depth = 3
  32. start_url = 'https://s.taobao.com/search?q=' + goods
  33. infoList = []
  34. for i in range(depth):
  35. try:
  36. url = start_url + '&s=' + str(44*i)
  37. html = getHTMLText(url)
  38. parsePage(infoList, html)
  39. except:
  40. continue
  41. printGoodsList(infoList)
  42. main()
實例2 股票數據爬蟲
     
     
     
             
  1. #CrawBaiduStocksB.py
  2. import requests
  3. from bs4 import BeautifulSoup
  4. import traceback
  5. import re
  6. def getHTMLText(url, code="utf-8"):
  7. try:
  8. r = requests.get(url)
  9. r.raise_for_status()
  10. r.encoding = code
  11. return r.text
  12. except:
  13. return ""
  14. def getStockList(lst, stockURL):
  15. html = getHTMLText(stockURL, "GB2312")
  16. soup = BeautifulSoup(html, 'html.parser')
  17. a = soup.find_all('a')
  18. for i in a:
  19. try:
  20. href = i.attrs['href']
  21. lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
  22. except:
  23. continue
  24. def getStockInfo(lst, stockURL, fpath):
  25. count = 0
  26. for stock in lst:
  27. url = stockURL + stock + ".html"
  28. html = getHTMLText(url)
  29. try:
  30. if html=="":
  31. continue
  32. infoDict = {}
  33. soup = BeautifulSoup(html, 'html.parser')
  34. stockInfo = soup.find('div',attrs={'class':'stock-bets'})
  35. name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
  36. infoDict.update({'股票名稱': name.text.split()[0]})
  37. keyList = stockInfo.find_all('dt')
  38. valueList = stockInfo.find_all('dd')
  39. for i in range(len(keyList)):
  40. key = keyList[i].text
  41. val = valueList[i].text
  42. infoDict[key] = val
  43. with open(fpath, 'a', encoding='utf-8') as f:
  44. f.write( str(infoDict) + '\n' )
  45. count = count + 1
  46. print("\r當前進度: {:.2f}%".format(count*100/len(lst)),end="")
  47. except:
  48. count = count + 1
  49. print("\r當前進度: {:.2f}%".format(count*100/len(lst)),end="")
  50. continue
  51. def main():
  52. stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
  53. stock_info_url = 'https://gupiao.baidu.com/stock/'
  54. output_file = 'D:/BaiduStockInfo.txt'
  55. slist=[]
  56. getStockList(slist, stock_list_url)
  57. getStockInfo(slist, stock_info_url, output_file)
  58. main()








免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM