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"01x+313C270204";
client-hostname"rac-ABCDEF";
}
lease10.127.1.253{
starts12012/08/2006:58:48;
ends32012/09/1906:58:48;
tstp32012/09/1906:58:48;
bindingstateactive;
nextbindingstatefree;
hardwareethernet11:22:33:44:55:84;
uid"01x+313C270204";
client-hostname"rac-AAAAA";
}'''

mth=re.findall(rex,txt,re.S)

forlinmth:
printl[0],l[1]

⑶ python簡單文本處理

最後結果中的 德國 總理那一行不知道怎麼來的,應該在 b.txt 中有同樣的前綴才對。


data=dict()

#processa.txt
forlineinopen("a.txt","r"):
k,s,v=line.partition("_")
ifs!="_":
continue
data[k.strip()]=[int(x)forxinv.split()]

defsum(a,b):
result=[]
maxlen=max(len(a),len(b))
foriinrange(maxlen):
v1=a[i]ifi<len(a)else0
v2=b[i]ifi<len(b)else0
result.append(v1+v2)
returnresult

#generatec.txt
fd=open("c.txt","w")
forlineinopen("b.txt","r"):
line=line.strip()
iflen(line)==0:
fd.write(" ")
continue

result=[]
forkinline.split():
result=sum(result,data.get(k,[0]))
fd.write("{}_{} ".format(line,''.join([str(i)foriinresult])))

fd.close()

⑷ python處理文本

myfile=open('filename')
keyword="1015838488"
haskeyword=False
toprint=[]
forlineinmyfile:
ifline.strip()=="":
ifhaskeyword:
print(''.join(toprint))
toprint=[]
haskeyword=False
ifkeywordinline:
haskeyword=True
toprint.append(line)
ifhaskeyword:
print(''.join(toprint))

將filename替換為實際的文件名

⑸ python 3 文本處理例子求代碼

#coding:utf-8
#file: FileSplit.py

import os,os.path,time

def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 1000 #每個小文件中保存100000條數據
dataLine = sFile.readline()
tempData = [] #緩存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目標目錄不存在,則創建
os.mkdir(targetFolder)
while dataLine: #有數據
for row in range(number):
tempData.append(dataLine) #將一行數據添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #創建小文件
tFile.writelines(tempData) #將列表保存到文件中
tFile.close()
tempData = [] #清空緩存列表
print(tFilename + " 創建於: " + str(time.ctime()))
fileNum += 1 #文件編號

sFile.close()

if __name__ == "__main__" :
FileSplit("access.log","access")
#coding:utf-8
#file: Map.py

import os,os.path,re

def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #緩存列表
if not os.path.isdir(targetFolder): #如果目標目錄不存在,則創建
os.mkdir(targetFolder)
while dataLine: #有數據
p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正則表達式解析數據
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #讀入下一行數據

sFile.close()

tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')

tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #創建小文件
tFile.writelines(tList) #將列表保存到文件中
tFile.close()

if __name__ == "__main__" :
Map("access\\access.log1.txt","access")
Map("access\\access.log2.txt","access")
Map("access\\access.log3.txt","access")
#coding:utf-8
#file: Rece.py

import os,os.path,re

def Rece(sourceFolder, targetFile):
tempData = {} #緩存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正則表達式解析數據
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()

while dataLine: #有數據
subdata = p_re.findall(dataLine) #用空格分割數據
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #讀入下一行數據

sFile.close()

tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')

tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #創建小文件
tFile.writelines(tList) #將列表保存到文件中
tFile.close()

if __name__ == "__main__" :
Rece("access","access")

⑹ python用腳本程序處理文本數據,提取。

spe=raw_input("inputyourorder")
n=0
withopen("1.txt",r)asA:
foreachlineinA:
tmp=eachline.rstrip().split(" ")
if(tmp[2]==spe):
n+=1
printn,tmp[5],tmp[1]," "

差不多這意思?就是把第三列為某個分類的物種全輸出來。

⑺ 求個文本處理的python程序,具體如下,萬分感謝!

樓主是不是應該把測試文件放上來,而不是貼張圖片,這樣我們樓下的也可以知道你測試文件的格式,包括行內的分隔符到底是空格還是製表符。在沒有測試文件的基礎下,只能提供一下思路:
首先需要把文件內容妥善的存儲到內存中,建議的格式是字典,字典的鍵是Cluster no, 字典的值是list,list的內容是文件的每一行。
之後定義函數開始處理,使用正則表達式匹配,匹配一次加1,直到滿足你刪除的條件,則直接返回一個標識符,從字典中刪除這個鍵值對。
最後把字典妥善存儲迴文件。

⑻ python文本處理

#encoding=utf8
importsys
reload(sys)
sys.setdefaultencoding('utf8')

a='test.txt'
withopen(a)asinfo:
text=info.readlines()
english=text[1].decode('gb2312')
chinese=text[2].decode('gb2312')
printenglish,chinese
foreachinenglish.split():
forotherinchinese.split():
print'{}@{}'.format(each,other)

剩下的你自己寫吧,主要的都寫完了

⑼ python如何用字元串實例化類

反射機制吧?其實直接用 globals() 這個函數就可以了,他可以返回所有全局對象的列表:專
>>> globals()
{'a': 'obj', 'obj': <class '__main__.obj'>, '__builtins__': <mole 'builtins' (
built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

所有直接對這個列表索引就可以屬獲得類了。
>>> globals()[a]
<class '__main__.obj'>
>>> globals()[a]()
<__main__.obj object at 0x00E5A350>