1. 程式人生 > >re模塊 ,random模塊

re模塊 ,random模塊

內容 one iter *** 測試的 括號 位數 mov import

# 在python中使用正則表達式
# 轉義符 : 在正則中的轉義符 \ 在python中的轉義符
# 正則表達式中的轉義 :
# ‘\(‘ 表示匹配小括號
# [()+*?/$.] 在字符組中一些特殊的字符會現出原形
# 所有的 \w \d \s(\n,\t, ) \W \D \S都表示它原本的意義
# [-]只有寫在字符組的首位的時候表示普通的減號
# 寫在其他位置的時候表示範圍[1-9]
# 如果就是想匹配減號 [1\-9]

# python中的轉義符
# 分析過程
‘\n‘ # \轉義符 賦予這個n一個特殊的意義 表示一個換行符
# print(‘\\n‘)
# print\\n(‘C:\\next‘)
# print(r‘C:\next‘)
# ‘\\\\n‘ ‘\\n‘
# 結論
# r‘\\n‘ r‘\n‘ 在python中



# 轉義符
# print(‘\n‘) # --> \\ \
# \ 是有特殊意義的
# 你看見了這個\ 不應該理解為這是一個‘\‘,它是一個轉義符
# 你想把這個轉義符變成一個字符串‘\‘,它必須經過轉義
# ‘\\‘ 等於字符串數據類型的‘\‘
# ‘\\n‘
# import re
# ret = re.search(‘\\\\n‘,‘\\n‘)
# print(ret)
# 如果一個字符串形式的‘\‘取消了它轉義符的意思,就表示一個字符串‘\‘
# 那麽就不需要再使用‘\\‘來表示‘\‘了
# 我們就在字符串前面加上一個r‘‘,取消這個字符串中所有‘\‘的轉義
# import re
# ret = re.search(r‘\\n‘,r‘\n‘)
# print(ret)

# 在測試的工具中,如果帶了\,你又擔心它會出現轉義的情況

# 不管三七二十一,在測試工具裏測好了的代碼
# 拿到python中,統一放在字符串r‘‘中就行了

***********************************************************************************************
# re模塊
# findall search match
# sub subn split
# compile finditer
# python中的正則表達式
# findall 會優先顯示分組中的內容,要想取消分組優先,(?:正則表達式)
# split 遇到分組 會保留分組內被切掉的內容
# search 如果search中有分組的話,通過group(n)就能夠拿到group中的匹配的內容
# import re
# 字符串

# 匹配
# findall *****
# ret = re.findall(‘\d+‘,‘19874ashfk01248‘)
# print(ret) # 參數 返回值類型:列表 返回值個數:1 返回值內容:所有匹配上的項
# ret1 = re.findall(‘\s+‘,‘19874ashfk01248‘)
# print(ret1)
# search *****
# ret2 = re.search(‘\d+‘,‘@$19874ashfk01248‘)
# print(ret2) # 返回值類型: 正則匹配結果的對象 返回值個數:1 如果匹配上了就返回對象
# if ret2:print(ret2.group()) # 返回的對象通過group來獲取匹配到的第一個結果
# ret3 = re.search(‘\s+‘,‘19874ashfk01248‘)
# print(ret3) # 返回值類型: None 如果沒有匹配上就是None
# match **
# ret4 = re.match(‘\d+‘,‘19874ashfk01248‘)
# print(ret4)
# ret5 = re.match(‘\d+‘,‘%^19874ashfk01248‘)
# print(ret5)


# 替換 replace
# sub ***
# print(‘replace789,24utdeedeeeeshf‘.replace(‘e‘,‘H‘,3))
# ret = re.sub(‘\d+‘,‘H‘,‘replace789nbc2xcz392zx‘)
# print(ret)
# ret = re.sub(‘\d+‘,‘H‘,‘replace789nbc2xcz392zx,48495‘,1)
# print(ret)
# subn ***
# ret = re.subn(‘\d+‘,‘H‘,‘replace789nbc2xcz392zx‘)
# print(ret)

# 切割
# split ***
# print(‘alex|83|‘.split(‘|‘))
# ret = re.split(‘\d+‘,‘alex83egon20taibai40‘)
# print(ret)

# 進階方法 - 爬蟲\自動化開發
# compile ***** 時間效率
# re.findall(‘-0\.\d+|-[1-9]+(\.\d+)?‘,‘alex83egon20taibai40‘) --> python解釋器能理解的代碼 --> 執行代碼
# ret = re.compile(‘-0\.\d+|-[1-9]\d+(\.\d+)?‘)
# res = ret.search(‘alex83egon-20taibai-40‘)
# print(res.group())
# 節省時間 : 只有在多次使用某一個相同的正則表達式的時候,這個compile才會幫助我們提高程序的效率
#
# finditer ***** 空間效率
# print(re.findall(‘\d‘,‘sjkhkdy982ufejwsh02yu93jfpwcmc‘))
# ret = re.finditer(‘\d‘,‘sjkhkdy982ufejwsh02yu93jfpwcmc‘)
# for r in ret:
# print(r.group())
*****************************************************************************************************
# 正則表達式進階
# 分組命名
# (?P<name>正則表達式) 表示給分組起名字
# (?P=name)表示使用這個分組,這裏匹配到的內容應該和分組中的內容完全相同
# 通過索引使用分組
# \1 表示使用第一組,匹配到的內容必須和第一個組中的內容完全相同
# import re
# ret = re.findall(‘-0\.\d+|-[1-9]\d*(\.\d+)?‘,‘-1asdada-200‘)
# print(ret)
# ret = re.findall(‘-100qweqwe-200)
# print(ret)
# ret = re.findall(‘www.(?:baidu|oldboy).com‘,‘www.oldboy.com‘) #?: 取消括號優先級
# print(ret)

# ret = re.findall(‘-0\.\d+|-[1-9]\d*(?:\.\d+)?‘,‘-1asdada-200‘)
# print(ret)

# ret = re.split(‘\d+‘,‘alex83egon20taibai40‘)
# print(ret)
# ret = re.split(‘(\d+)‘,‘alex83egon20taibai40‘)
# print(ret)

# 分組遇見search
# ret = re.search(‘\d+(.\d+)(.\d+)(.\d+)?‘,‘1.2.3.4-2*(60+(-40.35/5)-(-4*3))‘)
# print(ret.group())
# print(ret.group(1))
# print(ret.group(2))
# print(ret.group(3))

# import re
# ret = re.findall(‘>(\w+)<‘,r‘<a>wahaha<\a>‘)
# print(ret)

# ret = re.search(r‘<(?P<name>\w+)>(\w+)</(\w+)>‘,r‘<a>wahaha</b>‘)
# print(ret.group())
# print(ret.group(1))
# print(ret.group(2))

# 分組命名
# ret = re.search(r"<(?P<name>\w+)>\w+</(?P=name)>",r"<h1>hello</h1>")
# print(ret.group(‘name‘)) #結果 :h1
# # print(ret.group()) #結果 :<h1>hello</h1>
#
# ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
# print(ret.group(1))
# # print(ret.group()) #結果 :<h1>hello</h1>

# ret = re.search(r‘<(?P<tag>\w+)>(?P<c>\w+)</(\w+)>‘,r‘<a>wahaha</b>‘)
# print(ret.group())
# print(ret.group(‘tag‘))
# print(ret.group(‘c‘))

*****************************************************************************************
一段爬蟲代碼
import re
from urllib.request import urlopen
# 內置的包 來獲取網頁的源代碼 字符串
# res = urlopen(‘http://www.cnblogs.com/Eva-J/articles/7228075.html‘)
# print(res.read().decode(‘utf-8‘))

def getPage(url):
response = urlopen(url)
return response.read().decode(‘utf-8‘)

def parsePage(s): # s 網頁源碼
ret = com.finditer(s)
for i in ret:
ret = {
"id": i.group("id"),
"title": i.group("title"),
"rating_num": i.group("rating_num"),
"comment_num": i.group("comment_num")
}
yield ret

def main(num):
url = ‘https://movie.douban.com/top250?start=%s&filter=‘ % num # 0
response_html = getPage(url) # response_html是這個網頁的源碼 str
ret = parsePage(response_html) # 生成器
print(ret)
f = open("move_info7", "a", encoding="utf8")
for obj in ret:
print(obj)
data = str(obj)
f.write(data + "\n")
f.close()

com = re.compile(
‘<div class="item">.*?<div class="pic">.*?<em .*?>(?P<id>\d+).*?<span class="title">(?P<title>.*?)</span>‘
‘.*?<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?<span>(?P<comment_num>.*?)評價</span>‘, re.S)
count = 0
for i in range(10):
main(count) # count = 0
count += 25

********************************************************************************************************************
random 模塊


import random
# 隨機 : 在某個範圍內取到每一個值的概率是相同的
# 隨機小數
# print(random.random()) # 0-1之內的隨機小數
# print(random.uniform(1,5)) # 任意範圍之內的隨機小數

# 隨機整數 *****
# print(random.randint(1,2)) # [1,2] 包含2在內的範圍內隨機取整數
# print(random.randrange(1,2)) # [1,2)不包含2在內的範圍內隨機取整數
# print(random.randrange(1,10,2)) # [1,10)不包含10在內的範圍內隨機取奇數

# 隨機抽取
# 隨機抽取一個值
# lst = [1,2,3,‘aaa‘,(‘wahaha‘,‘qqxing‘)]
# ret = random.choice(l)
# print(ret)
# 隨機抽取多個值
# ret = random.sample(lst,2)
# print(ret)

# 打亂順序 在原列表的基礎上做亂序
# lst = [1,2,3,‘aaa‘,(‘wahaha‘,‘qqxing‘)]
# random.shuffle(lst)
# print(lst)

# 抽獎 \ 彩票 \發紅包 \驗證碼 \洗牌

# 生成隨機驗證碼
# 4位數字的
import random
# 0-9
# 基礎版本
# code = ‘‘
# for i in range(4):
# num = random.randint(0,9)
# code += str(num)
# print(code)

# 函數版本
# def rand_code(n=4):
# code = ‘‘
# for i in range(n):
# num = random.randint(0,9)
# code += str(num)
# return code
#
# print(rand_code())
# print(rand_code(6))

# 6位 數字+字母
# print(chr(97))
# print(chr(122))
# import random

# 基礎版
# code = ‘‘
# for i in range(6):
# rand_num = str(random.randint(0,9))
# rand_alph = chr(random.randint(97,122))
# rand_alph_upper = chr(random.randint(65,90))
# atom_code = random.choice([rand_num,rand_alph,rand_alph_upper])
# code += atom_code
# print(code)

# 函數版
# def rand_code(n=6):
# code = ‘‘
# for i in range(n):
# rand_num = str(random.randint(0,9))
# rand_alph = chr(random.randint(97,122))
# rand_alph_upper = chr(random.randint(65,90))
# atom_code = random.choice([rand_num,rand_alph,rand_alph_upper])
# code += atom_code
# return code
#
# ret = rand_code()
# print(ret)

# 數字/數字+字母
# def rand_code(n=6 , alph_flag = True):
# code = ‘‘
# for i in range(n):
# rand_num = str(random.randint(0,9))
# if alph_flag:
# rand_alph = chr(random.randint(97,122))
# rand_alph_upper = chr(random.randint(65,90))
# rand_num = random.choice([rand_num,rand_alph,rand_alph_upper])
# code += rand_num
# return code
#
# ret = rand_code(n = 6)
# print(ret)

# ***** 永遠不要創建一個和你知道的模塊同名的文件名

re模塊 ,random模塊