python文本處理實例
發布時間: 2021-03-10 08:54:45
⑴ python 處理文本,格式化文本~
#coding=utf-8
records=[]
record={}
withopen("data.txt")asf:
whileTrue:
line=f.readline()
ifnotline:
iflen(record)!=0:records.append(record)
break
field=line[line.find(":")+1:].strip()
ifline.startswith("ScopeId"):
iflen(record)!=0:records.append(record)
record={}
record["ScopeId"]=field
elifline.startswith("Name"):
record["Name"]=field
elifline.startswith("Free"):
record["Free"]=field
elifline.startswith("InUse"):
record["InUse"]=field
elifline.startswith("PercentageInUse"):
record["PercentageInUse"]=field
#設置預設項
forrinrecords:
r.setdefault("InUse",0)
r.setdefault("PercentageInUse",0)
r.setdefault("Name","")
r.setdefault("Free",0)
printrecords
⑵ python 文本處理難題,只能用PYHTON解決,代碼最優美效率最高的,謝謝
importre
rex=r'lease(.*?){.*?client-hostname"(.*?)";'
txt='''
lease10.127.1.254{
starts12012/08/2006:58:48;
ends32012/09/1906:58:48;
tstp32012/09/1906:58:48;
bindingstateactive;
nextbindingstatefree;
hardwareethernet11:22:33:44:55:84;
uid"