2 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
工作代碼如下:
lines_data = []
with open('ltm.txt', 'r') as logfile:
pairs = {}
for line in logfile:
new_entry = False
if line[0].isspace():
fields = line.strip().split(':')
else:
double_colon_idx = line.find('::')
line = line[double_colon_idx+2:]
new_entry = True
fields = line.strip().split(':')
if new_entry and pairs:
lines_data.append(pairs)
pairs = {}
if len(fields) >= 2:
key = fields[0]
value = fields[1]
pairs[key.strip()] = value.strip()
lines_data.append(pairs)
headers = lines_data[0].keys()
header_str = ','.join(headers)
with open('report.csv','w') as out:
out.write(header_str + '\n')
for entry in lines_data:
_line = []
for key in headers:
_line.append(entry[key])
out.write(','.join(_line) + '\n')
ltm.txt文件
Ltm::Virtual Server: acme.com
Availability : offline
State : enabled
Reason : The children pool member(s) are down
Destination : 10.1.1.2:80
Ltm::Virtual Server: foo.com
Availability : available
State : enabled
Reason : The virtual server is available
Destination : 10.100.11.15:80
Ltm::Virtual Server: hamhamspam.com
Availability : offline
State : enabled
Reason : The children pool member(s) are down
Destination : 10.200.8.17:443
報(bào)告.csv
Virtual Server,Availability,State,Reason,Destination
acme.com,offline,enabled,The children pool member(s) are down,10.1.1.2
foo.com,available,enabled,The virtual server is available,10.100.11.15
hamhamspam.com,offline,enabled,The children pool member(s) are down,10.200.8.17

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
您的代碼中有不同的問(wèn)題。
您嘗試拆分':',而其中一個(gè)鍵確實(shí)包含冒號(hào)。你應(yīng)該分開(kāi)': '
您始終嘗試拆分兩次,第一次是行(正確),然后是每個(gè)字段(錯(cuò)誤)。您應(yīng)該在拆分后刪除一個(gè)split并剝離:
...
for line in logfile:
row = line.split(': ')
key = row[0].strip()
fields.add(key)
其他功能相同
您分別處理每一行,而以空格字符開(kāi)頭的行是續(xù)行。你應(yīng)該只提取一對(duì)key, value并返回它:
def extract_pair(line):
key, value = line.split(': ')
return key.strip(), value.strip()
然后在你的主要部分,你必須處理續(xù)行
...
d = None
for line in logfile:
key, value = extract_pair(line)
if line[0].isspace():
d[key] = value # continuation line: update d
else:
if d is not None: # write full previous row
csvwriter.writerow([d[cell] for cell in header])
d = {key: value} # initial line: reset d
if d is not None: # process last row
csvwriter.writerow([d[cell] for cell in header])
添加回答
舉報(bào)