python 生涯之常用模組 (二)

來源:互聯網
上載者:User

標籤:文章   write   name   金融   admin   known   簡單的   Shelve模組   sage   

json & pickle 模組

用於序列化的兩個模組

  • json,用於字串 和 python資料類型間進行轉換
  • pickle,用於python特有的類型 和 python的資料類型間進行轉換

Json模組提供了四個功能:dumps、dump、loads、load

pickle模組提供了四個功能:dumps、dump、loads、load

 

shelve 模組

shelve模組是一個簡單的k,v將記憶體資料通過檔案持久化的模組,可以持久化任何pickle可支援的python資料格式

import shelved = shelve.open(‘shelve_test‘) #開啟一個檔案 class Test(object):    def __init__(self,n):        self.n = nt = Test(123)  t2 = Test(123334)name = ["alex","rain","test"] d["test"] = name #持久化列表d["t1"] = t      #持久化類d["t2"] = t2d.close()
xml處理模組

xml是實現不同語言或程式之間進行資料交換的協議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統公司如金融行業的很多系統的介面還主要是xml。

xml的格式如下,就是通過<>節點來區別資料結構的:

1234567891011121314151617181920212223 <?xml version="1.0"?><data>    <country name="Liechtenstein">        <rank updated="yes">2</rank>        <year>2008</year>        <gdppc>141100</gdppc>        <neighbor name="Austria" direction="E"/>        <neighbor name="Switzerland" direction="W"/>    </country>    <country name="Singapore">        <rank updated="yes">5</rank>        <year>2011</year>        <gdppc>59900</gdppc>        <neighbor name="Malaysia" direction="N"/>    </country>    <country name="Panama">        <rank updated="yes">69</rank>        <year>2011</year>        <gdppc>13600</gdppc>        <neighbor name="Costa Rica" direction="W"/>        <neighbor name="Colombia" direction="E"/>    </country></data>

 

xml協議在各個語言裡的都 是支援的,在python中可以用以下模組操作xml   

import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml")root = tree.getroot()print(root.tag)#遍曆xml文檔for child in root:    print(child.tag, child.attrib)    for i in child:        print(i.tag,i.text)#只遍曆year 節點for node in root.iter(‘year‘):    print(node.tag,node.text)

修改和刪除xml文檔內容

import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml")root = tree.getroot()#修改for node in root.iter(‘year‘):    new_year = int(node.text) + 1    node.text = str(new_year)    node.set("updated","yes")tree.write("xmltest.xml")#刪除nodefor country in root.findall(‘country‘):   rank = int(country.find(‘rank‘).text)   if rank > 50:     root.remove(country)tree.write(‘output.xml‘)

自己建立xml文檔

import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist")name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})age = ET.SubElement(name,"age",attrib={"checked":"no"})sex = ET.SubElement(name,"sex")sex.text = ‘33‘name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})age = ET.SubElement(name2,"age")age.text = ‘19‘et = ET.ElementTree(new_xml) #產生文檔對象et.write("test.xml", encoding="utf-8",xml_declaration=True)ET.dump(new_xml) #列印產生的格式 
ConfigParser模組

用於產生和修改常見配置文檔,當前模組的名稱在 python 3.x 版本中變更為 configparser。

來看一個好多軟體的常見文檔格式如下

[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no

如果想用python產生一個這樣的文檔怎麼做呢?

import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,                      ‘Compression‘: ‘yes‘,                     ‘CompressionLevel‘: ‘9‘}config[‘bitbucket.org‘] = {}config[‘bitbucket.org‘][‘User‘] = ‘hg‘config[‘topsecret.server.com‘] = {}topsecret = config[‘topsecret.server.com‘]topsecret[‘Host Port‘] = ‘50022‘     # mutates the parsertopsecret[‘ForwardX11‘] = ‘no‘  # same hereconfig[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘with open(‘example.ini‘, ‘w‘) as configfile:   config.write(configfile)

  

寫完了還可以再讀出來哈。

>>> import configparser>>> config = configparser.ConfigParser()>>> config.sections()[]>>> config.read(‘example.ini‘)[‘example.ini‘]>>> config.sections()[‘bitbucket.org‘, ‘topsecret.server.com‘]>>> ‘bitbucket.org‘ in configTrue>>> ‘bytebong.com‘ in configFalse>>> config[‘bitbucket.org‘][‘User‘]‘hg‘>>> config[‘DEFAULT‘][‘Compression‘]‘yes‘>>> topsecret = config[‘topsecret.server.com‘]>>> topsecret[‘ForwardX11‘]‘no‘>>> topsecret[‘Port‘]‘50022‘>>> for key in config[‘bitbucket.org‘]: print(key)...usercompressionlevelserveraliveintervalcompressionforwardx11>>> config[‘bitbucket.org‘][‘ForwardX11‘]‘yes‘

configparser增刪改查文法

[section1]k1 = v1k2:v2 [section2]k1 = v1import ConfigParser config = ConfigParser.ConfigParser()config.read(‘i.cfg‘) # ########## 讀 ###########secs = config.sections()#print secs#options = config.options(‘group2‘)#print options #item_list = config.items(‘group2‘)#print item_list #val = config.get(‘group1‘,‘key‘)#val = config.getint(‘group1‘,‘key‘) # ########## 改寫 ###########sec = config.remove_section(‘group1‘)#config.write(open(‘i.cfg‘, "w")) #sec = config.has_section(‘wupeiqi‘)#sec = config.add_section(‘wupeiqi‘)#config.write(open(‘i.cfg‘, "w"))  #config.set(‘group2‘,‘k1‘,11111)#config.write(open(‘i.cfg‘, "w")) #config.remove_option(‘group2‘,‘age‘)#config.write(open(‘i.cfg‘, "w"))
hashlib模組  

用於加密相關的操作,3.x裡代替了md5模組和sha模組,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 演算法

import hashlibm = hashlib.md5()m.update(b"Hello")m.update(b"It‘s me")print(m.digest())m.update(b"It‘s been a long time since last time we ...")print(m.digest()) #2進位格式hashprint(len(m.hexdigest())) #16進位格式hash‘‘‘def digest(self, *args, **kwargs): # real signature unknown    """ Return the digest value as a string of binary data. """    passdef hexdigest(self, *args, **kwargs): # real signature unknown    """ Return the digest value as a string of hexadecimal digits. """    pass‘‘‘import hashlib# ######## md5 ########hash = hashlib.md5()hash.update(‘admin‘)print(hash.hexdigest())# ######## sha1 ########hash = hashlib.sha1()hash.update(‘admin‘)print(hash.hexdigest())# ######## sha256 ########hash = hashlib.sha256()hash.update(‘admin‘)print(hash.hexdigest())# ######## sha384 ########hash = hashlib.sha384()hash.update(‘admin‘)print(hash.hexdigest())# ######## sha512 ########hash = hashlib.sha512()hash.update(‘admin‘)print(hash.hexdigest())

還不夠吊?python 還有一個 hmac 模組,它內部對我們建立 key 和 內容 再進行處理然後再加密

散列訊息鑒別碼,簡稱HMAC,是一種基於訊息鑒別碼MAC(Message Authentication Code)的鑒別機制。使用HMAC時,訊息通訊的雙方,通過驗證訊息中加入的鑒別密鑰K來鑒別訊息的真偽;

一般用於網路通訊中訊息加密,前提是雙方先要約定好key,就像接頭暗號一樣,然後訊息發送把用key把訊息加密,接收方用key + 訊息明文再加密,拿加密後的值 跟 寄件者的相對比是否相等,這樣就能驗證訊息的真實性,及寄件者的合法性了。

 

import hmach = hmac.new(b‘天王蓋地虎‘, b‘寶塔鎮河妖‘)print h.hexdigest()

更多關於md5,sha1,sha256等介紹的文章看這裡https://www.tbs-certificates.co.uk/FAQ/en/sha256.html 

re模組

常用Regex符號

‘.‘預設匹配除\n之外的任意一個字元,若指定flag DOTALL,則匹配任一字元,包括換行‘^‘匹配字元開頭,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)‘$‘匹配字元結尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以‘*‘匹配*號前的字元0次或多次,re.findall("ab*","cabb3abcbbac")  結果為[‘abb‘, ‘ab‘, ‘a‘]‘+‘匹配前一個字元1次或多次,re.findall("ab+","ab+cd+abb+bba") 結果[‘ab‘, ‘abb‘]‘?‘匹配前一個字元1次或0次‘{m}‘匹配前一個字元m次‘{n,m}‘匹配前一個字元n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果‘abb‘, ‘ab‘, ‘abb‘]‘|‘匹配|左或|右的字元,re.search("abc|ABC","ABCBabcCD").group()結果‘ABC‘‘(...)‘ 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c‘\A‘只從字元開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的‘\Z‘匹配字元結尾,同$‘\d‘匹配數字0-9‘\D‘匹配非數字‘\w‘匹配[A-Za-z0-9]‘\W‘匹配非[A-Za-z0-9]‘s‘匹配空白字元、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 ‘\t‘‘(?P<name>...)‘ 分組匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 結果{‘province‘: ‘3714‘, ‘city‘: ‘81‘, ‘birthday‘: ‘1993‘}

  

最常用的匹配文法

re.match 從頭開始匹配re.search 匹配包含re.findall 把所有匹配到的字元放到以列表中的元素返回re.splitall 以匹配到的字元當做清單分隔符號re.sub匹配字元並替換 

反斜線的困擾
與大多數程式設計語言相同,Regex裡使用"\"作為逸出字元,這就可能造成反斜線困擾。假如你需要匹配文本中的字元"\",那麼使用程式設計語言表示的Regex裡將需要4個反斜線"\\\\":前兩個和後兩個分別用於在程式設計語言裡轉義成反斜線,轉換成兩個反斜線後再在Regex裡轉義成一個反斜線。Python裡的原生字串很好地解決了這個問題,這個例子中的Regex可以使用r"\\"表示。同樣,匹配一個數位"\\d"可以寫成r"\d"。有了原生字串,你再也不用擔心是不是漏寫了反斜線,寫出來的運算式也更直觀。

 

僅需輕輕知道的幾個匹配模式

re.I(re.IGNORECASE): 忽略大小寫(括弧內是完整寫法,下同)M(MULTILINE): 多行模式,改變‘^‘和‘$‘的行為(參見)S(DOTALL): 點任意匹配模式,改變‘.‘的行為

python 生涯之常用模組 (二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.