2016-10-04 116 views
0

我有很長的文本文件,其中我能夠掠只包含單詞「平均」的那些提取這些行:文本數據轉換爲csv蟒蛇

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. 

這裏是我的HA但它並沒有給我正確的結果:

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

你有進口'json'對JSON'csv'爲CSV – MatejMecka

+0

模塊那麼,什麼地方出了錯:你可能有這樣的事情做的更好?這個文件中是否有多個項目?它們是否一致(即它們總是以相同的順序?)。發佈足夠的數據,以便我們可以獲得一些記錄。 – tdelaney

回答

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 
0

這將有助於向我們展示你做了什麼輸出與你所期望的。然而它看起來像我正在寫str(entry)到文件,其中entry是一個字典,並期待它呈現爲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)