2013-10-17 71 views
0

我想使用Python將普通結構化文本文件轉換爲CSV格式。Python:將結構化文本解析爲CSV格式

輸入看起來像這樣

[-------- 1 -------] 
Version: 2 
Stream: 5 
Account: A 
[...] 
[------- 2 --------] 
Version: 3 
Stream: 6 
Account: B 
[...] 

輸出應該是這個樣子:

Version; Stream; Account; [...] 
2; 5; A; [...] 
3; 6; B; [...] 

即輸入是由[----<sequence number>----]劃分的結構化文本記錄,其中包含<key>: <values>-對,輸出應該是CSV,每行包含一條記錄。

我能夠通過

colonseperated = re.compile(' *(.+) *: *(.+) *') 
fixedfields = re.compile('(\d{3} \w{7}) +(.*)') 

以檢索的<key>: <values> -pairs成CSV格式 - 但我的結構化文本記錄故障識別開始和結束與重新書寫爲CSV線 - 記錄。此外,我希望能夠分離不同類型的記錄,即區分 - 例如 - Version: 2Version: 3記錄類型。

+0

您輸入的文件不是* CSV格式;它是結構化的,但不是分隔符分隔的。您的輸出*是*。 –

+0

你對不同版本的記錄有何期待? –

+0

不同類型的記錄具有不同數量的元素。 –

回答

1

閱讀列表並不難:

def read_records(iterable): 
    record = {} 
    for line in iterable: 
     if line.startswith('[------'): 
      # new record, yield previous 
      if record: 
       yield record 
      record = {} 
      continue 
     key, value = line.strip().split(':', 1) 
     record[key.strip()] = value.strip() 

    # file done, yield last record 
    if record: 
     yield record 

這從您的輸入文件生成字典。

從這裏就可以使用csv模塊生成CSV輸出,特別是csv.DictWriter() class

# List *all* possible keys, in the order the output file should list them 
headers = ('Version', 'Stream', 'Account', ...) 

with open(inputfile) as infile, open(outputfile, 'wb') as outfile: 
    records = read_records(infile) 

    writer = csv.DictWriter(outfile, headers, delimiter=';') 
    writer.writeheader() 

    # and write 
    writer.writerows(records) 

任何標題密鑰從記錄丟失將離開該列空該記錄。任何額外您錯過的標題將引發異常;將其添加到headers元組中,或將extrasaction關鍵字設置爲DictWriter()的構造函數爲'ignore'

+0

感謝您提供寶貴的解釋性提示。我現在有一個工作原型。還有一個問題。使用全部標題(大約100),沒有適當的輸出只產生一行錯誤映射的字段:是否對'csv(headers)'有限制? –

+0

不是我所知道的;聽起來像別的東西可能是錯誤的。 –

相關問題