1. 程式人生 > >常用模塊之 re shutil configparser hashlib xldt和xlwd

常用模塊之 re shutil configparser hashlib xldt和xlwd

包含 表格 str 所在 pil 作用 RoCE 類型 abcd

shutil
高級文件處理模塊
封裝的更簡單了
主要是文件的復制,移動,壓縮解壓縮

需要保證目標文件已經存在
shutil.copymode(‘test.txt‘,‘testcopy4.txt‘)

壓縮與解壓縮

base_name 指定壓縮文件的名字
默認把當前執行文件所在目錄全部壓縮

如果同時指定了 root和base base生效 並且會把需要壓縮的文件的完整路徑一並壓縮



re
regexp 正則表達式
正則表達式是什麽
由一堆特殊符號責成的表達式
作用
處理字符串
1.從字符串中獲取滿足某種規則的內容 在爬蟲程序中大量出現
2.判斷一個字符串內容是否滿足某個規則 例如:手機號驗證,郵箱驗證
學習的重點就是圍繞這一堆符號

import re
re.findall(‘\w‘,‘abcd 12345 ++--**‘)
只要是大寫字符 就是與小寫字符相反的意思

. 除了\n外的所有字符
單個字符匹配

重復匹配 數字 字母下劃線

* 表示0-無窮次
0次也滿足 則意味著 就算內容沒有任何內容匹配也會給你一個空字符 因為空字符也算0次匹配

從網絡中下載一個HTML文檔,從裏面提取所需要的內容


+ 表示 1-無窮次
{a,b}最少a次 最多b次
{1,} 1-無窮與+的意思相同
{,2} 0-2
{1,2} 1-2
{,1} 0-1與?意思相同
* 0-無窮(隨便幾次)
+ 1-無窮
? 0-1次
{} 手動指定匹配次數


位置匹配 ^ $
^從字符開始出匹配
$從字符結尾處匹配
1.是先到最後看一眼是不是與表達式匹配 如果不匹配直接放棄
2.如果結尾處沒問題 在回過頭來從前面開始匹配

^與$同事出現 同事限定開始出和結尾處

範圍匹配 可以指定哪些內容是你要的 劃一個範圍
a|b


模仿 \w 數字 字母 下劃線[0-9a-zA-Z_]


貪婪匹配 與非貪婪匹配
貪婪指的是 盡可能的匹配更多的內容
非貪婪指的是 盡可能的匹配少的內容

貪婪的例子
print(re.findall(‘ab+‘,‘‘))
非貪婪的例子
print(re.findall(‘ab+?‘,‘‘))
print(re.findall(‘ab*?‘,‘‘))



htm = """<img src="http://img.ivsky.com/img/tupian/t/201808/07/qingting-001.jpg" alt="輕盈停落的蜻蜓圖片">
title="輕盈停落的蜻蜓圖片 3996x2664" target="_blank"><img src="http://img.ivsky.com/img/tupian/t/201808/07/qingting-002.jpg">
"""

貪婪模式會一次性取到最後一個雙引號為止
print(re.findall(‘src=".+"‘,htm))

加上?變成費貪婪模式
print(re.findall(‘src=".+?"‘,htm))

分組把要的內容加括號
print(re.findall(‘src="(.+?)"‘,htm))

當我們需要從一個匹配結果中拿到多個不同部分是 可以加多個分組
findall會把這些部分放到元組中
print(re.findall((‘src=)"(.+?)"‘,htm))


re.search().group()
也是全文查找 但是只返回 找到的第一個


re.match
從字符串開始匹配 第一個不匹配直接放棄 與^效果相同

p=re.compile(‘ab‘)
將表達式打包成對象 這樣可以多次使用無需重新編寫


re.sub()
替換內容
待處理字符串 舊的內容 新的內容


import re
# print(re.findall(‘\w‘,‘1511a3dsf1a5df /-/-*/-*/‘))


# print(re.findall(‘\D‘,‘-//a-s*df/-a*sd/f-*as/d-f*as/df-af‘))


# print(re.findall(‘\w?‘,‘aaavvvcd‘))
# print(re.findall(‘\w+‘,‘aaavvvcd‘))
# print(re.findall(‘\w*‘,‘aaavvvcd‘))
# print(re.findall(‘\w{,2}‘,‘aaavvvcd‘))


# print(re.findall(‘[^0-9]‘,‘13213212321abc_+*‘))
# print(re.findall(‘[-a-z0-9]‘,‘-s0‘))


# import configparser
# cfg=configparser.ConfigParser()
# cfg.read("my.cfg",encoding=‘utf-8‘)
#
# print(cfg.sections())#獲取所有分區名字
# print(cfg.get(‘ATM‘,‘username‘))#獲取某個選項的值
# print(cfg.get(‘ATM‘,‘password‘))#獲取某個選項的值

# def login():
#     user=input(‘用戶名:‘).strip()
#     pwd =input(‘密碼:‘).strip()

  



hashlib
unhashable 不可hash 是可變的
hash 是一種算法
特點:
1.輸入任意長度的數據 輸出固定長度的字符串 因此也稱之為信息摘要算法
2.hash算法有很多實現方式 當算法固定時,如果輸入相同,那麽輸出結果必然相同
(極小的幾率會出現,不同的輸入產生相同的結果)
3.無法通過hash的結果反解出原數據

使用場景
1.可以用於加密
2.用於文件校驗

import hashlib
創建一個加密對象
m=hashlib.md5()
計算123456的hash值
m.update(‘123456‘.encode(‘utf-8‘))
提取加密結果
print(len(m.hedigest()))

update 可以多次執行 也就意味著你可以打開文件 讀一次就調用一次update
簡單的密碼可以通過撞庫破解,所以我們最好給密碼加點鹽,在原有的數據基礎上加上一段固定的數據

subprocess
子進程
進程就是一個正在運行的程序
一個進程a在運行過程中開啟了另一個進程b
b就稱之為a的子進程
當你的程序在運行過程中又一個任務,不能直接處理需要其他程序
提供幫助時就需要開啟子進程
import subprocess
subprocess.Popen(‘dir‘,shell=True,stdout=subprocess.PIPE)
res=p.stdout
print(res.decode(‘GBK‘))


subprocess 模塊的目的就是要使得子進程(執行了一個系統指令)可以把數據輸出到我的程序中

configparser
配置文件解析模塊
配置應用程序的文件
配置信息指的是 程序中有一些數據根據用戶自己來指定 不應該固定死 比如qq中開機啟動這一個數據
這就需要配置文件
對於配置文件而言,我們的程序最常見的就是讀取配置文件操作
當然configparser 模塊也能修改和創建配置文件 但不常用
# 所有選項獲取的到的都是字符串類型
print(type(cfg.get("atm","password")))

# 提供了 getint getboolean get float 可以直接幫你轉換類
print(cfg.getint("atm","age"))
print(type(cfg.getint("atm","age")))

# 判斷是否存在分區 或 選項
print(cfg.has_option("atm","age"))
print(cfg.has_section("atm"))

# 獲取某個分區下的所有選項
print(cfg.options("atm"))
# 刪除分區 和選項
print(cfg.remove_section("car"))
print(cfg.remove_option("atm","sex"))

# 修改或是添加 如果有就修改 沒有則添加
cfg.set("atm","age","30")

# 添加分區
cfg.add_section("test")
cfg.set("test","賬號","大山炮")


# 寫入文件
with open("my.cfg","wt",encoding="utf-8") as f:
cfg.write(f)


option

配置ATM
[ATM] 稱之為一個分區 section
username=root
password=123

[shopping_car]
配置購物車
username=root

所有的選項獲取到的都是字符串類型
提供了getint getboolean get float可以直接幫你轉換類


代碼

import configparser
import os

def login():
if exists_usercfg():
cfg = configparser.ConfigParser()
cfg.read("user.cfg",encoding="utf-8")
user = cfg.get("info","username")
pwd = cfg.get("info","password")
else:
user = input("用戶名:")
pwd = input("密碼:")

if user == "李大炮" and pwd == "213":
print("登錄成功!")
if not exists_usercfg():
res = input("是否記住密碼?y/n")
if res == "y":
jzmm(user,pwd)

# 記住密碼函數
def jzmm(user,pwd):
cfg = configparser.ConfigParser()
cfg.add_section("info")
cfg.set("info","username",user)
cfg.set("info","password",pwd)

with open("user.cfg","wt",encoding="utf-8") as f:
cfg.write(f)

def exists_usercfg():
if os.path.exists("user.cfg"):
return True

login()


xlrd 讀取excle表格數據
xlwt 寫入數據到excel表格中


import xlrd
讀取文件 得到一個工作簿對象
work_book=xlrd.open_workbook(‘xxx.xlsx‘)
sheet=work_book.sheet_by_index(1)
sheet.row 第一行所有
sheet.row_len 第一行的幾個單元格
sheet.row_slice(1) 第二行所有
sheet.row_slice(1,2,4)第二行索引2-4不包含4
第一個是行索引 第二個是開始列索引 第三個是結束的列索引

print(sheet.row_values(6,0,4))獲取某些段遠哥的數據值

有幾行就循環幾次
for i in range(sheet.nrows)
print(i)
通過索引拿到每一行
print(sheet.row_slice(i))
for cell in sheet.row_slice(i)
在每一行中取出每一個單元格
print(cell.value)
print(cell.ctype)

將這個表格的數據轉成字典類型
1.先拿到所有的key
keys = [cell.value for cell in sheet.row_slice(1)]
print(keys)

for i in range(2,sheet.nrows):
# 有幾次循環就有幾個人員信息
# 建立一個新字典
dic = {}
rows = sheet.row_slice(i)
key_index = 0
for cell in rows:
if key_index == 3: #說明是日期 需要轉換
dic[keys[key_index]] = str(xlrd.xldate_as_datetime(cell.value,1))
else:
dic[keys[key_index]] = cell.value
key_index += 1
persons.append(dic)



import xlwt
# 創建工作簿
work = xlwt.Workbook()
# 創建一個表
sheet = work.add_sheet("員工信息數據")

# 寫入標題
for k in keys:
# 行索引 列索引 第三個是要寫入的數據
sheet.write(0,keys.index(k),k)

# 寫入數據
for i in persons:
for k in keys:
sheet.write(1 + persons.index(i),keys.index(k),label = i[k])
# 保存至文件
work.save("test.xls")

常用模塊之 re shutil configparser hashlib xldt和xlwd