1. 程式人生 > >Python之旅.第四章.模塊與包4.09

Python之旅.第四章.模塊與包4.09

port 換行符 earch re模塊 shel bytes fda count sub


一、shelve模塊
Shelve(了解),是更高程度的封裝。使用時只針對之前設計生成的文件,可以無視不同平臺自動生成的其他文件。
 
Json的中間格式為字符串,用w寫入文件
Pickle的中間格式為bytes,用b寫入文件
序列化時更常用Json
 
import shelve
info1={‘age‘:18,‘height‘:180,‘weight‘:80}
info2={‘age‘:73,‘height‘:150,‘weight‘:80}
 
d=shelve.open(‘db.shv‘)
d[‘egon‘]=info1
d[‘alex‘]=info2
d.close()
 
d=shelve.open(‘db.shv‘)
print(d[‘egon‘])
print(d[‘alex‘])
d.close()
 
d=shelve.open(‘db.shv‘,writeback=True)
d[‘alex‘][‘age‘]=10000
print(d[‘alex‘])
d.close()
 
d=shelve.open(‘db.shv‘,writeback=True) #如果想改寫,需設置writeback=True
print(d[‘alex‘])
d.close()

二、xml模塊
xml時一種組織數據的形式
xml下的元素對應三個特質,tag, attrib, text
 
#==========================================>查
import xml.etree.ElementTree as ET
 
tree=ET.parse(‘a.xml‘)
root=tree.getroot()
三種查找節點的方式
res=root.iter(‘rank‘) # 會在整個樹中進行查找,而且是查找到所有
for item in res:
    print(‘=‘*50)
    print(item.tag) # 標簽名
    print(item.attrib) #屬性
    print(item.text) #文本內容
 
res=root.find(‘country‘) # 只能在當前元素的下一級開始查找。並且只找到一個就結束
print(res.tag)
print(res.attrib)
print(res.text)
nh=res.find(‘neighbor‘)
print(nh.attrib)
 
cy=root.findall(‘country‘) # 只能在當前元素的下一級開始查找,
print([item.attrib for item in cy])
 
#==========================================>改
import xml.etree.ElementTree as ET
tree=ET.parse(‘a.xml‘)
root=tree.getroot()
 
for year in root.iter(‘year‘):
    year.text=str(int(year.text) + 10)
    year.attrib={‘updated‘:‘yes‘}   #一般不會改tag
 
tree.write(‘a.xml‘)
 
#==========================================>增
import xml.etree.ElementTree as ET
tree=ET.parse(‘a.xml‘)
root=tree.getroot()
 
for country in root.iter(‘country‘):
    year=country.find(‘year‘)
    if int(year.text) > 2020:
        print(country.attrib)
        ele=ET.Element(‘egon‘)
        ele.attrib={‘nb‘:‘yes‘}
        ele.text=‘非常帥‘
        country.append(ele)
        country.remove(year)
tree.write(‘b.xml‘)
 
三、re模塊(正則)

正則---在爬蟲中最為常用;使用爬蟲時有其他模塊可以導入幫助clear數據,正則也可用於其他方面
import re
print(re.findall(‘\w‘,‘ab 12\+- *&_‘))
print(re.findall(‘\W‘,‘ab 12\+- *&_‘))
print(re.findall(‘\s‘,‘ab \r1\n2\t\+- *&_‘))
print(re.findall(‘\S‘,‘ab \r1\n2\t\+- *&_‘))
print(re.findall(‘\d‘,‘ab \r1\n2\t\+- *&_‘))
print(re.findall(‘\D‘,‘ab \r1\n2\t\+- *&_‘))
print(re.findall(‘\w_sb‘,‘egon alex_sb123123wxx_sb,lxx_sb‘))
print(re.findall(‘\Aalex‘,‘abcalex is salexb‘))
print(re.findall(‘\Aalex‘,‘alex is salexb‘))
print(re.findall(‘^alex‘,‘alex is salexb‘))
print(re.findall(‘sb\Z‘,‘alexsb is sbalexbsb‘))
print(re.findall(‘sb$‘,‘alexsb is sbalexbsb‘))
print(re.findall(‘^ebn$‘,‘ebn1‘)) #^ebn$ 篩出的就是ebn(以ebn開頭,以ebn結尾)
print(re.findall(‘a\nc‘,‘a\nc a\tc a1c‘))
 
\t為制表符,在不同平臺表示不同的空個數
\A ó ^     #使用^
\Z ó $     #使用$
 
# 重復匹配:
#.   ?   *   +  {m,n}  .*  .*?
1、.:代表除了換行符外的任意一個字符
. 除了換行符之外的任意一個字符, 如果想不除換行符,後加re.DOTALL
 
print(re.findall(‘a.c‘,‘abc a1c aAc aaaaaca\nc‘))
print(re.findall(‘a.c‘,‘abc a1c aAc aaaaaca\nc‘,re.DOTALL))
 
2、?:代表左邊那一個字符重復0次或1次
?不能單獨使用
 
print(re.findall(‘ab?‘,‘a ab abb abbb abbbb abbbb‘))
 
3、*:代表左邊那一個字符出現0次或無窮次
print(re.findall(‘ab*‘,‘a ab abb abbb abbbb abbbb a1bbbbbbb‘))
 
4、+ :代表左邊那一個字符出現1次或無窮次
print(re.findall(‘ab+‘,‘a ab abb abbb abbbb abbbb a1bbbbbbb‘))
 
5、{m,n}:代表左邊那一個字符出現m次到n次
print(re.findall(‘ab?‘,‘a ab abb abbb abbbb abbbb‘))
print(re.findall(‘ab{0,1}‘,‘a ab abb abbb abbbb abbbb‘))
print(re.findall(‘ab*‘,‘a ab abb abbb abbbb abbbb a1bbbbbbb‘))
print(re.findall(‘ab{0,}‘,‘a ab abb abbb abbbb abbbb a1bbbbbbb‘))
print(re.findall(‘ab+‘,‘a ab abb abbb abbbb abbbb a1bbbbbbb‘))
print(re.findall(‘ab{1,}‘,‘a ab abb abbb abbbb abbbb a1bbbbbbb‘))
print(re.findall(‘ab{1,3}‘,‘a ab abb abbb abbbb abbbb a1bbbbbbb‘))
 
6、.*:匹配任意長度,任意的字符=====》貪婪匹配
print(re.findall(‘a.*c‘,‘ac a123c aaaac a *123)()c asdfasfdsadf‘))
 
7、.*?:非貪婪匹配
print(re.findall(‘a.*?c‘,‘a123c456c‘))
 
():分組
print(re.findall(‘(alex)_sb‘,‘alex_sb asdfsafdafdaalex_sb‘))
print(re.findall(
    ‘href="(.*?)"‘,
    ‘<li><a id="blog_nav_sitehome" class="menu" href="http://www.cnblogs.com/">博客園</a></li>‘)
)
 
[]:匹配一個指定範圍內的字符(這一個字符來自於括號內定義的)
[] 內寫什麽就是其單獨的意義, 可寫0-9 a-zA-Z
print(re.findall(‘a[0-9][0-9]c‘,‘a1c a+c a2c a9c a11c a-c acc aAc‘))
 
當-需要被當中普通符號匹配時,只能放到[]的最左邊或最 右邊
a-b有特別的意思,所以如果想讓-表示它本身,要將其放在最左或最右
print(re.findall(‘a[-+*]c‘,‘a1c a+c a2c a9c a*c a11c a-c acc aAc‘))
print(re.findall(‘a[a-zA-Z]c‘,‘a1c a+c a2c a9c a*c a11c a-c acc aAc‘))
 
[]內的^代表取反的意思 (^在[]中表示取反)
print(re.findall(‘a[^a-zA-Z]c‘,‘a c a1c a+c a2c a9c a*c a11c a-c acc aAc‘))
print(re.findall(‘a[^0-9]c‘,‘a c a1c a+c a2c a9c a*c a11c a-c acc aAc‘))
print(re.findall(‘([a-z]+)_sb‘,‘egon alex_sb123123wxxxxxxxxxxxxx_sb,lxx_sb‘))
 
| :或者
print(re.findall(‘compan(ies|y)‘,‘Too many companies have gone bankrupt, and the next one is my company‘))
 
(?:   ):代表取匹配成功的所有內容,而不僅僅只是括號內的內容 ((?:   )表示匹配的結果都要,不單單要()內的)
print(re.findall(‘compan(?:ies|y)‘,‘Too many companies have gone bankrupt, and the next one is my company‘))
print(re.findall(‘alex|sb‘,‘alex sb sadfsadfasdfegon alex sb egon‘))
 
re模塊的其他方法:
print(re.findall(‘alex|sb‘,‘123123 alex sb sadfsadfasdfegon alex sb egon‘))
print(re.search(‘alex|sb‘,‘123213 alex sb sadfsadfasdfegon alex sb egon‘).group())
print(re.search(‘^alex‘,‘123213 alex sb sadfsadfasdfegon alex sb egon‘))
print(re.search(‘^alex‘,‘alex sb sadfsadfasdfegon alex sb egon‘).group())
re.search, 取第一個結果,若沒有返回None;若想讓結果直接顯示後加group();返回None時用group()會報錯
 
print(re.match(‘alex‘,‘alex sb sadfsadfasdfegon alex sb egon‘).group())
print(re.match(‘alex‘,‘123213 alex sb sadfsadfasdfegon alex sb egon‘))
re.match 相當於^版本的search
 
info=‘a:b:c:d‘
print(info.split(‘:‘))
print(re.split(‘:‘,info))
 
info=r‘get :a.txt\3333/rwx‘
print(re.split(‘[ :\\\/]‘,info))
re.split與split相比,內部可以使用正則表達式
 
print(‘egon is beutifull egon‘.replace(‘egon‘,‘EGON‘,1))
print(re.sub(‘(.*?)(egon)(.*?)(egon)(.*?)‘,r‘\1\2\3EGON\5‘,‘123 egon is beutifull egon 123‘))
 
print(re.sub(‘(lqz)(.*?)(SB)‘,r‘\3\2\1‘,r‘lqz is SB‘))
print(re.sub(‘([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)‘,r‘\5\2\3\4\1‘,r‘lqzzzz123+ is SB‘))
re.sub 與replace相比,內部可以使用正則表達式
 
pattern=re.compile(‘alex‘)
print(pattern.findall(‘alex is alex alex‘))
print(pattern.findall(‘alexasdfsadfsadfasdfasdfasfd is alex alex‘))

Python之旅.第四章.模塊與包4.09