2016-11-12 35 views
0

我對python很新,有一些問題,我似乎無法找到答案。 我有一個大文件,我正在嘗試閱讀,然後分割並寫出特定信息。我在讀入和分割時遇到問題,它只是一遍又一遍地打印相同的東西。閱讀一個文件,分裂,然後寫出所需的輸出

blast_output = open("blast.txt").read() 
for line in blast_output: 
    subFields = [item.split('|') for item in blast_output.split()] 
    print(str(subFields[0][0]) + "\t" + str(subFields[0][1]) + "\t" + str(subFields[1][3]) + "\t" + str(subFields[2][0])) 

我的輸入文件有看起來像這樣的多行:

c0_g1_i1|m.1 gi|74665200|sp|Q9HGP0.1|PVG4_SCHPO  100.00 372  0  0  1  372  1  372  0.0  754 
c1002_g1_i1|m.801  gi|1723464|sp|Q10302.1|YD49_SCHPO  100.00 646  0  0  1  646  1  646  0.0  1310 
c1003_g1_i1|m.803  gi|74631197|sp|Q6BDR8.1|NSE4_SCHPO  100.00 246  0  0  1  246  1  246  1e-179 502 
c1004_g1_i1|m.804  gi|74676184|sp|O94325.1|PEX5_SCHPO  100.00 598  0  0  1  598  1  598  0.0  1227 

我收到的輸出是這樣的:

c0_g1_i1 m.1 Q9HGP0.1 100.00 
c0_g1_i1 m.1 Q9HGP0.1 100.00 
c0_g1_i1 m.1 Q9HGP0.1 100.00 
c0_g1_i1 m.1 Q9HGP0.1 100.00 

但是我想是

c0_g1_i1  m.1 Q9HGP0.1 100.0 
c1002_g1_i1 m.801 Q10302.1 100.0 
c1003_g1_i1 m.803 Q6BDR8.1 100.0 
c1004_g1_i1 m.804 O94325.1 100.0 
+1

您應該使用line.split()在第三行。 – giliev

+0

'blast_output'是一個字符串,遍歷一個字符串給你的字符,而不是行。在開始處移除'.read()'以迭代文件的行。 –

+0

嘗試*展開* /擴展您的列表理解並將所有這些字段分配給變量。然後你可以檢查單個變量(也許用打印語句)來查看發生了什麼。 – wwii

回答

1

您不需要調用文件對象的read方法,只需逐行地遍歷它即可。然後用line在更換blast_output for循環,以避免在所有迭代重複同樣的動作:

with open("blast.txt") as blast_output: 
    for line in blast_output: 
     subFields = [item.split('|') for item in line.split()] 
     print("{:15}{:10}{:10}{:10}".format(subFields[0][0], subFields[0][1], 
              subFields[0][1], subFields[1][3], subFields[2][0])) 

我已經打開使用with上下文的文件,因此關閉自動被Python完成。我還使用字符串格式來構建最終的字符串。


c0_g1_i1  m.1  m.1  Q9HGP0.1 
c1002_g1_i1 m.801  m.801  Q10302.1 
c1003_g1_i1 m.803  m.803  Q6BDR8.1 
c1004_g1_i1 m.804  m.804  O94325.1 
1

偉大的問題。您正在使用這條線一遍又一遍地走的是相同的輸入

subFields = [item.split('|') for item in blast_output.split()] 

蟒蛇2.x的版本,看起來是這樣的:

blast_output = open("blast.txt").read() 
for line in blast_output: 
    subFields = [item.split('|') for item in line.split()] 
    print(str(subFields[0][0]) + "\t" + str(subFields[0][1]) + "\t" + str(subFields[1][3]) + "\t" + str(subFields[2][0])) 

見智Koledoye的版本,一個爲Python 3.x的格式化正派

+0

謝謝,這澄清了爲什麼它不起作用。我猜我正在使用的文本顯示版本2,但我需要版本3 :) –

相關問題