2017-09-15 38 views
-1

所以我試圖用一個「column_matches」函數來搜索帶有數據的txt文件,該數據是存儲在數組中的,用於列中特定值然後打印包含該值的行。在製表符分隔的數組中搜索一列以獲取特定值

我的代碼現在看起來是這樣的:

f = open(r'file_directory') 
a = [] 
for line in f: 
    a.append(line) 

def column_matches(line, substring, which_column): 
     for line in a: 
      if column_matches(line, '4', 6): 
       print (line) 
      else: 
       print('low multiplicity') 

在這個例子中,我試圖尋找第7列的值4。然而,這是目前沒有任何打印。 我是一名初學者程序員,所以這可能是非常錯誤的,但會喜歡一些反饋,因爲我無法從其他人的問題中解決它。 理想情況下,程序應搜索所有行並在特定列中打印(或保存)每行具有特定值的行!

編輯:例如輸入:

K00889.01 0.9990 8.884922995 10.51 0.114124 89.89 1 153 0.8430 0.8210

K01009.01 0.0000 5.09246539 1.17 0.014236 89.14 1 225 0.7510 0.7270

+1

你不是在調用函數'column_matches()',除了它本身。我不確定'column_matches'應該如何工作,因爲函數中包含的唯一邏輯依賴於它自己的輸出。 – roganjosh

+0

在完成構建列表之後,在定義函數之前,還有'print(a [0] [6])'',print(type(a [0] [6]))'的輸出是什麼?你調用第二個參數「substring」,然後提供一個整數,所以我不確定你想要匹配什麼,你沒有提供任何示例輸入。 – roganjosh

+0

@roganjosh ,所以是的,我猜它應該是'4'。打印(a [0] [6])由於某種原因不會返回任何內容。 –

回答

0

你的現有功能沒有按」 t實際上有任何邏輯來處理您要搜索的案例。事實上,你有if column_matches(line, '4', 6):裏面函數column_matches所以你暗示,它必須調用自己,以確定採取什麼行動......邏輯上只是形成一個無限循環(雖然在你的情況,實際上沒有運行)。

這應該是類似於您現有的方法,但應該做你想做的。它應該對你的實際文件結構相對有彈性,但是讓我知道它是否會引發錯誤。

data = [] 
with open('example.txt', 'r') as infile: 
    # Will automatically close the file once you're done reading it 
    for row in infile: 
     data.append(row.replace('\n', '').split()) 


def column_matches(line, target, column_index): 
    try: 
     file_data = int(line[column_index]) 
     if file_data == target: 
      return True 
     else: 
      return False 
    except ValueError: 
     print('Not a valid number: {}'.format(line[column_index])) 
     return False 

matching_rows = [] # To store items in data that meet our criteria 
for line in data: 
    if column_matches(line, 4, 6): 
     matching_rows.append(line) # Function has to return True for this to happen 
+0

這工作完美!並且容易遵循。不勝感激! –

相關問題