1. 程式人生 > >day023 正則表示式和re模組

day023 正則表示式和re模組

一.正則
1.字元組
[a-zA-Z0-9]字元組中的  [^a] 除了字元組的

2. 

3.

4.


二.re模組
re.S   設定   .的換行       obj=re
1.ret=re.search(正則,content)   找到一個結果就返回  
  拿到結果 需要.group ret.group()
2.ret=re.match(正則,content) 從頭匹配. 如果匹配到了。 就返回
  也需要 ret.group()
3.ret=re.findall(正則,content) 匹配到的結果全部放入列表中 ,下級元素以元組存放
import re

ret = re.findall('www.(baidu|oldboy).com', 'www.oldboy.com')
print(ret)  # ['oldboy']     這是因為findall會優先把匹配結果組裡內容返回,如果想要匹配結果,取消許可權即可

ret = re.findall('www.(?:baidu|oldboy).com', 'www.oldboy.com')
print(ret)  # ['www.oldboy.com']
findall優先順序查詢

4.ret=re.finditer(正則,content) 得到一個迭代
器,迴圈迭代器時,取值時,也要 用group

for el in ret:
  el.group()
5.re.split(正則,字串) 用正則中的每個元素分別進行切割
ret=re.split("\d+","eva3egon4yuan")
print(ret) #結果 : ['eva', 'egon', 'yuan']

ret=re.split("(\d+)","eva3egon4yuan")
print(ret) #結果 : ['eva', '3', 'egon', '4', 'yuan']

#在匹配部分加上()之後所切出的結果是不同的,
#沒有()的沒有保留所匹配的項,但是有()的卻能夠保留了匹配的項,
#這個在某些需要保留匹配部分的使用過程是非常重要的。
split優先順序查詢
 
6.re.sub(正則,new,字串)  替換  用新的 替換符合正則的元素
7.re.subn(正則,new,字串) 替換 用新的 替換符合正則的元素替換。 返回的結果帶有次數
8. obj=re.compile(正則) 預載入 正則 lst=obj.findall(content)
  obj=re.compile(r"start.*?(?P<自定義名字>.*j)end",re.S)
import re

res = re.search("e", "alex and exp") # 搜尋. 搜到結果就返回
print(res.group())

res = re.match("\w+", "alex is not a good man") #  從頭匹配.  如果匹配到了。 就返回
print(res.group())

lst = re.findall("\w+", "alex and exo")
print(lst)

it = re.finditer("\w+", "mai le fo leng")
for el in it:
    print(el.group())

# # 這個分組是優先順序
lst = re.findall(r"www\.(baidu|oldboy)\.com", "www.oldboy.com")
print(lst)

# (?: )  去掉優先順序
lst = re.findall(r"www\.(?:baidu|oldboy)\.com", "www.oldboy.com")
print(lst)

# 加了括號。 split會保留你切的刀
lst = re.split("([ab])", "alex is not a sb, no he is a big sb") # 根據正則表示式進行切割
print(lst)
#
# # 替換
res = re.sub(r"\d+", "_sb_", "alex333wusir666taibai789ritian020feng")
print(res)
#
# # 替換。 返回的結果帶有次數
res = re.subn(r"\d+", "_sb_", "alex333wusir666taibai789ritian020feng")
print(res)

a = eval("1+3+5+6")
print(a)

code = "for i in range(10):print(i)"
c = compile(code, "", "exec") # 編譯程式碼
exec(c)

obj = re.compile(r"alex(?P<name>\d+)and") # 把正則表示式預載入
res = obj.search("alex250andwusir38ritian2")
print(res.group())
print(res.group("name"))
re模組
import re
from urllib.request import urlopen

#正則
obj=re.compile(r'<div class="item">.*? <a href=(?P<URL>.*?)">.*?<span class="title">(?P<name>.*?)</span>'
               r'.*?<span class="rating_num" property="v:average">(?P<fen>.*?)</span>.*?<span>(?P<pingjia>.*?)人評價</span>',re.S)

#獲取網頁內容函式 
def get_content(url):
    content=urlopen(url).read().decode("utf-8")
    return content

#獲取網頁所要內容轉化成字典的函式
def parse(content):
    g=obj.finditer(content)  
    for el in g:
        yield {
            '電影名':el.group("name"),
            'url':el.group("URL"),
            '評分':el.group('fen'),
            '評價人數':el.group("pingjia")
        }

#分頁爬取 
for i in range(10):  
    url="https://movie.douban.com/top250?start=%s&filter="%i*25  #每頁的url  每頁共25部電影
    g=parse(get_content(url))
    f=open("dian.txt","a",encoding="utf-8")
    for el in g:
        f.write(str(el)+"\n")
        # print(el)
    f.close()
爬豆瓣
import re
from urllib.request import urlopen
import json
url="https://www.dytt8.net/"
content=urlopen(url).read().decode("gbk")
obj=re.compile(r"最新電影下載</a>]<a href='(?P<URL>.*?)'>.*?《(?P<name>.*?)》",re.S)
obj2=re.compile(r'<!--Content Start--><span style="FONT-SIZE: 12px"><td>.*?'
                r'【下載地址】</font></font></strong> <br /><br /><br /><a href=".*?(?P<xiazai>.*?)"><strong>',re.S)

lst=obj.findall(content)

f=open("movie",'w',encoding="utf-8")
for el in lst:
    try:
       dic= {"name":el[1],"URL":"https://www.dytt8.net"+el[0]}
       url2=dic["URL"]
       content2=urlopen(url2).read().decode("gbk")
       dz=obj2.search(content2).group("xiazai")
       dic2={"name":dic["name"],"地址":dz}
       s=json.dumps(dic2,ensure_ascii=False)
       f.write(s+"\n")
       print(dic)
    except Exception as e:
        continue
f.close()
爬電影天堂