0


【Python】对原始输入文件(./raw.txt)进行信息的提取和整理

【简答题】假设原始输入文件 (./raw.txt)的内容如下所示:


r644 | Mary | 2016-03-27 18:30:22 +0800 (Tue, 29 Mar 2016) |
Error: fix refine issue


r584 | John | 2016-03-24 11:34:52 +0800 (Tue, 29 Mar 2016) |
Info: add more trb


r575 | David | 2016-03-23 10:36:34 +0800 (Tue,29 Mar 2016) |
Info: update case


请使用—种编程语言(如Python, Perl, C,C++等)编写一段代码对原始文件进行信息的提取和整理,运行后的效果如下所示

Error Count: 1
Info Count: 2
Error:
Mary | r644 | 2016-03-27 | fix refine issue
Info:
John | r584 | 2016-03-24 | add more trb
David | r575 | 2016-03-23 | update case

你选的编程语言是: 【Python】
代码:

import os
def get_time(time):
    times = time.split(" ")
    print(times)
    return times[1]
def get_data(data,info):
    datas = data.split("|")
    ID = datas[0]
    NAME = datas[1]
    TIME = get_time(datas[2])
    infos = info.split(":")
    INFO = infos[1]
    return NAME +" | " + ID +" | " +TIME +" | " + INFO
    
rf = open("raw.txt","r") 
lines = rf.readlines()      #读取全部内容 ,并以列表方式返回
text = ''
error_list = []
info_list = []
for line in lines:
    if(line.find('Error')!= -1):
        index = lines.index(line)-1
        error_list.append(get_data(lines[index],line))
        get_data(lines[index],line)
    elif(line.find('Info') != -1):
        index = lines.index(line)-1
        info_list.append(get_data(lines[index],line))
        #print(line)
       
text += "Error Count: " + str(len(error_list))+"\n"
text += "Info Count: " + str(len(info_list))+"\n"
text += "Error:" + "\n"
for err in error_list:
    text += err 

text += "Info:" + "\n"
for info in info_list:
    text += info

#导出
with open('res.txt','w') as f:
    f.write(text)

本文转载自: https://blog.csdn.net/luolaihua2018/article/details/120346521
版权归原作者 SOC罗三炮 所有, 如有侵权,请联系我们删除。

“【Python】对原始输入文件(./raw.txt)进行信息的提取和整理”的评论:

还没有评论