2016-05-24 14 views
0

次のように表示される.txtファイルを読み込み、新しい整数リスト行列に変換するコードを記述する必要があります。ただし、手動でファイルを削除せずに、この.txtファイルの最初の行をスキップします。私はそれを行う方法がわかりません。 私はいくつかのコードを書いています。行列を表示することができるが、私は最初の行を取り除くことができません:しばらく前にPythonでファイルの最初の行をスキップする方法

def display_matrix(a_matrix): 
    for row in a_matrix: 
     print(row) 
    return a_matrix 

def numerical_form_of(a_list): 
    return [int(a_list[i]) for i in range(len(a_list))] 

def get_scoring_matrix(): 
    scoring_file = open("Scoring Matrix") 
    row_num = 0 
    while row_num <= NUMBER_OF_FRAGMENTS: 
     content_of_line = scoring_file.readline() 
     content_list = content_of_line.split(' ') 
     numerical_form = numerical_form_of(content_list[1:]) 
     scoring_matrix = [] 
     scoring_matrix.append(numerical_form) 
     row_num += 1 
     #print(scoring_matrix) 
     display_matrix(scoring_matrix) 
    # (Complement): row_num = NUMBER_OF_FRAGMENTS 
    return scoring_matrix 

get_scoring_matrix() 

Scoring Matrix is a .txt file: 
    1 2 3 4 5 6 7 
1 0 1 1 1 1 1 1 
2 0 0 1 1 1 1 1 
3 0 0 0 1 1 1 1 
4 0 0 0 0 1 1 1 
5 0 0 0 0 0 1 1 
6 0 0 0 0 0 0 1 
7 0 0 0 0 0 0 0 

The result of my code: 
[1, 2, 3, 4, 5, 6, 7] 
[0, 1, 1, 1, 1, 1, 1] 
[0, 0, 1, 1, 1, 1, 1] 
[0, 0, 0, 1, 1, 1, 1] 
[0, 0, 0, 0, 1, 1, 1] 
[0, 0, 0, 0, 0, 1, 1] 
[0, 0, 0, 0, 0, 0, 1] 
[0, 0, 0, 0, 0, 0, 0] 

答えて

2

私は、自動化ツール使用することをお勧め:あなたはそれを自分でやって主張する場合、whileループを変更

import pandas 
df = pandas.read_table("Scoring Matrix", delim_whitespace = True) 

を。

while row_num <= NUMBER_OF_FRAGMENTS: 
     content_of_line = scoring_file.readline() 
     if row_num == 0: 
      content_of_line = scoring_file.readline() 
+0

うわー、ありがとうございました! whileループの動作を変更しますが、最後の行が空のリストを表示する理由: [0、0、1、1、1、1] [0、1、1、1、1、1] 、0,0,1,1,1] [0,0,0,0,1,1,1] [0,0,0,0,1,1] [0,0 、0、0、0、0] [0,0,0,0,0,0,0] [] –

+0

@ZichenMaファイルの最後に余分な改行がある可能性があります最後の行のいくつかのスペース。 – gt6989b

+0

ありがとう! –

3

がちょうど(scoring_file.readlineを置きます)ループ。

関連する問題