2017-01-13 80 views
-1

如果我們有一個文本文件,如下所示:閱讀文本文件分成幾個列表一行行

6 & ロク3 & サン 
9 & キュウ 
0 & ゼロ5 & ゴ 
7 & ナナみぎ & ミギひだり & ヒダリ 
うえ & ウエ 

一個人怎麼能讀入蟒蛇得到一個列表的方式,每個「列」像這樣的:

a = ["6", "9", "0", "7", "うえ"] 
b = ["ロク3" , "キュウ", "ゼロ5", "ナナみぎ", "ウエ"] 
c = ["サン", "", "ゴ}", "ミギひだり", ""] 
d = ["", "ヒダリ", "", "", ""] 
+0

拆分並追加到單獨的列表,然後打印這些列表。 –

回答

1

嘗試了這一點:

with open(path, 'r') as inputFile: 
    lines = list() 

    for line in inputFile: 
     lines.append(line.split("&")) 

    maxLen = len(max(lines, key=lambda x: len(x))) 

    for line in lines: 
     while len(line) < maxLen: 
      line.append(" ") 

    column0 = [line[0] for line in lines] 
    column1 = [line[1] for line in lines] 
    . 
    . 
    . 

另外,如果你想在「細胞」擺脫空白的,使用replace方法:

without_spaces = with_spaces.replace(" ", "") 

要使用它,只需更換

lines.append(line.split("&")) 

lines.append(line.replace(" ", "").split("&")) 
1

itertools.izip_longest將是任務非常方便。

import itertools 

def cleanup(alist): 
    return [item.strip() for item in alist] 

with open('input.txt', 'r') as input_file: 
    lines = input_file.readlines() 
    contents = [cleanup(line.split('&')) for line in lines] 
    zipped = itertools.izip_longest(*contents, fillvalue='') 

    for column in zipped: 
     print column 

請注意zipped實際上是所有列的迭代器。