我有一个很长的文本文件,我可以通过抓取包含“Average”一词的那些来提取这些行:
Average time per layer:
Average Forward pass: 4013.65 ms.
Average Backward pass: 7425.13 ms.
Average Forward-Backward: 11480.2 ms.
这是我在csv文件中需要的内容,因此我可以轻松制作图表:
Average Forward pass 4013.65
Average Backward pass 7425.13
Average Forward-Backward 11480.2
以下是我得到的输出:
: 7425.13 ms.
: 11480.2 ms.
:
: 4013.65 ms.
这是我所拥有的,但它没有给我正确的结果:
def parse_output(outputName):
"This reads the parsed file and formated it to a map"
with open(outputName,'r') as parsedFile:
entry = {}
for line in parsedFile:
key, value = map(line.strip, line.split(':',1))
entry[key] = value
yield entry
def print_csv(outputName, csvFile):
"This reads the map and print it to csv"
remove_file_exist(csvFile)
for foo in parse_output(outputName):
with open(csvFile, 'a') as csvFile:
for entry in foo:
csvFile.write(str(entry))
print(entry)
print(foo);
我试图将原始文本转换为json,但没有让它工作。任何输入都会欣赏它。我对python非常新。这是我用这种语言编写的第一个脚本。
答案 0 :(得分:1)
这将有助于向我们展示您获得的输出与您期望的结果。但是,在我看来,您正在将str(entry)
写入文件,其中entry
是一个dict,并期望它呈现为csv行。我怀疑它看起来会更像每行一个JSON对象。
每当你想在Python中编写或读取csv时,csv模块通常是一个很好的第一站。你可能会用这样的东西做得更好:
import csv
def parse_output(outputname):
with open(outputname, 'r') as output:
for row in output:
yield [field.strip() for field in row.split(':', 1)]
def print_csv(outputname, csvname):
with open(csvname, 'wb') as csvfile:
csvfile = csv.writer(csvfile)
for parsedline in parse_output(outputname):
csvfile.write(parsedline)
答案 1 :(得分:0)
您可以对此类数据使用regex:
txt='''\
Average time per layer:
Average Forward pass: 4013.65 ms.
Average Backward pass: 7425.13 ms.
Average Forward-Backward: 11480.2 ms.'''
import re
for k,v in re.findall(r'^([^:]+):\s*(\d+\.\d+)', txt, re.M):
print k, v