第19次全天課筆記 20181202 json
第19次全天課筆記 20181202 WiFi密碼:46702126
正則表示式練習
1 統計文章的字母個數
>>> re.findall(r"[a-zA-Z]","ab 78 cd 69\n")
['a', 'b', 'c', 'd']
>>> len(re.findall(r"[a-zA-Z]","ab 78 cd 69\n"))
4
2統計文章數字個數
>>> len(re.findall(r"\d","ab 78 cd 69\n"))
4
3統計文章中的單詞個數
>>> len(re.findall(r"\b[a-zA-Z]+\b","ab 78 cd 69\n"))
2
4統計文章單詞個數
5獲取某個網頁的所有連結
re.findall(r'href="(.*?)"',s)
6 刪除文章中所有數字
>>> re.sub(r"\d+","","a123 a56789")
'a a'
7 刪除後統計一下刪除個數
>>> re.subn(r"\d+","","a123 b456 c789")
('a b c', 3)
>>> re.subn(r"\d+","","a123 b456 c789")[1]
3
8 匹配一個ip
re.match(r"([2][0-4][0-9]\.|[2][5][0-5]\.|[1][0-9]{2}\.|[1-9][0-9]{0,1}\.|0\.)([2][0-4][0-9]\.|[2][5][0-5]\.|[1][0-9]{2}\.|[1-9][0-9]{0,1}\.|0\.)([2][0-4][0-9]\.|[2][5][0-5]\.|[1][0-9]{2}\.|[1-9][0-9]{0,1}\.|0\.)([2][0-4][0-9]|[2][5][0-5]|[1][0-9]{2}|[1-9][0-9]{0,1}(?!\d)|0)"," 255.20.255.255")
或((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]) #還要加上259 不匹配25
9 統計開頭不是a的所有單詞
>>> re.findall(r"\b(?!a)[a-zA-Z]+\b","abc cde fgi 2ad ")
['cde', 'fgi']
10 匹配1900年到2999年
>>> re.match(r"(19\d{2}|2\d{3})年","1920年")
<_sre.SRE_Match object; span=(0, 5), match='1920年'>
Json串
#coding=utf-8
import json
data= [ { 'a':'A', 'b':(2, 4), 'c':3.0, (1,2):'D tuple' } ]
print(u"不設定skipkeys 引數")
try :
res1 = json.dumps(data) #skipkeys引數預設為False時
except Exception as e:
print(e)
print(u"設定skipkeys 引數")
print(json.dumps(data, skipkeys=True))# skipkeys=True時
>>> import json
>>> print (json.dumps('中國’))
"\u4e2d\u56fd"
>>> print (json.dumps('中國',ensure_ascii=False))
"中國"
>>> #coding=utf-8
... import json
>>> data = [{'a':"Aasdf",'b':(2,4),'c':3.0}]
>>> data_json = json.dumps(data)
>>> print("encoding :", data_json)
encoding : [{"a": "Aasdf", "b": [2, 4], "c": 3.0}]
>>> print("decoding :", json.loads(data_json))
decoding : [{'a': 'Aasdf', 'b': [2, 4], 'c': 3.0}]
#encoding=utf-8
import json
class Employee(object):
def __init__(self, name, age, sex, tel):
self.name = name
self.age = age
self.sex = sex
self.tel = tel
# 將序列化函式定義到類裡面
def obj_json(self, obj_instance):
return {
'name': obj_ instance.name,
'age': obj_instance.age,
'sex': obj_instance.sex,
'tel': obj_ instance.tel }
emp = Employee('Lily', 24, 'female', '18223423423')
print(json.dumps(emp, default = emp.obj_json))
#encoding=utf-8
import json
class Employee(object):
def __init__(self, name, age, sex, tel):
self.name = name
self.age = age
self.sex = sex
self.tel = tel
emp = Employee('Lily', 24, 'female', '18223423423')
print(emp.__dict__)
print(json.dumps(emp, default = lambda Employee: Employee.__dict__))
print(json.dumps(emp, default = lambda emp: emp.__dict__))
#encoding=utf-8
import json
class Employee(object):
def __init__(self, name, age, sex, tel):
self.name = name
self.age = age
self.sex = sex
self.tel = tel
emp = Employee('Lily', 24, 'female', '18223423423')
def jsonToClass(emp):
return Employee(emp['name'], emp['age'], emp['sex'], emp['tel'])
json_str = '{"name": "Lucy", "age": 21, "sex": "female", "tel": "15834560985"}'
e = json.loads(json_str, object_hook = jsonToClass)
print(e)
print( e.name)
深入淺出MySql,紅白相間
XML
判斷節點是文字還是element
D:\up\1202
>>> isinstance(books[0].childNodes[0],xml.dom.minidom.Text)
True
>>> isinstance(books[0].childNodes[1],xml.dom.minidom.Element)
True
#從xml.dom.minidom模組引入解析器parse
from xml.dom.minidom import parse
DOMTree = parse("movies.xml")
movielist = DOMTree.documentElement
movies = movielist.getElementsByTagName("movie")
#遍歷movies節點,找到movie節點下的子節點,然後列印值
for movie in movies:
if movie.hasAttribute("title") and movie.getAttribute("title")=="Trigun":
print (movie.getAttribute("title"))
for i in movie.childNodes[1::2]:
print (i.tagName,end=":")
print (i.childNodes[0].data)
#coding=utf-8
import xml.dom.minidom
#在記憶體中建立一個空的文件
doc = xml.dom.minidom.Document()
#建立一個根節點company物件
root = doc.createElement('companys')
# 給根節點root新增屬性
root.setAttribute('name', u'公司資訊')
#將根節點新增到文件物件中
doc.appendChild(root)
# 給根節點新增一個葉子節點
company = doc.createElement('gloryroad')
# 葉子節點下再巢狀葉子節點
name = doc.createElement("Name")
# 給節點新增文字節點
name.appendChild(doc.createTextNode(u"光榮之路教育科技公司"))
ceo = doc.createElement('CEO')
ceo.appendChild(doc.createTextNode(u'吳總'))
# 將各葉子節點新增到父節點company中
# 然後將company新增到跟節點companys中
company.appendChild(name)
company.appendChild(ceo)
root.appendChild(company)
fp = open('e:\\company.xml', 'w',encoding='utf-8')
doc.writexml(fp, indent='', addindent='\t', newl='\n', encoding="utf-8")
fp.close()
#coding=utf-8
import xml.dom.minidom
#在記憶體中建立一個空的文件
doc = xml.dom.minidom.Document()
#建立一個根節點Managers物件
root = doc.createElement('Managers')
#設定根節點的屬性
root.setAttribute('company', 'xx科技')
root.setAttribute('address', '科技軟體園')
#將根節點新增到文件物件中
doc.appendChild(root)
managerList = [{'name' : 'joy', 'age' : 27, 'sex' : '女'},
{'name' : 'tom', 'age' : 30, 'sex' : '男'},
{'name' : 'ruby', 'age' : 29, 'sex' : '女'} ]
for i in managerList :
nodeManager = doc.createElement('manager')
nodeName = doc.createElement('name')
#給葉子節點name設定一個文字節點,用於顯示文字內容
nodeName.appendChild(doc.createTextNode(str(i['name'])))
nodeAge = doc.createElement("age")
nodeAge.appendChild(doc.createTextNode(str(i["age"])))
nodeSex = doc.createElement("sex")
nodeSex.appendChild(doc.createTextNode(str(i["sex"])))
#將各葉子節點新增到父節點Manager中,
#最後將Manager新增到根節點Managers中
nodeManager.appendChild(nodeName)
nodeManager.appendChild(nodeAge)
nodeManager.appendChild(nodeSex)
root.appendChild(nodeManager)
#開始寫xml文件
fp = open('D:\\up\\1202\\company1.xml', 'w',encoding='utf-8')
doc.writexml(fp, indent='', addindent='\t', newl='\n', encoding="utf-8")
fp.close()