2016-02-13 101 views
3

我想編寫一個程序,打印出一個值超過另一個值的特定行/行線。例如,這是文本文件中的一小部分:如何根據條件(大於或小於)打印出文本文件中的特定行/行

01,test1,202,290,A,290 

02,test2,303,730,A,0 

03,test3,404,180,N,180 

,我想代碼將選擇具有「A」在他們的所有行,但還可以選擇線,其中第4列的程序(290對於第一線)大於在第一行的第6列(290),然後打印them.So程序應該只打印在上面蟒蛇在文本文件中這一行:

02,test2,303,730,A,0 

盡我所能do只是使用以下內容打印所有具有「A」的行:

F = open("TEST.txt").read() 
    for line in F.split(): 
    if 'A' in line: 
     Column=line.split(',') 

但是,這隻會選擇'A'在他們的行,當我試圖根據第4列是否大於第6列進行過濾時,我得到各種錯誤。有人可以幫我解決這個問題嗎?

回答

1

csv LIB將文件解析爲行對你來說,你應該也從來沒有像琴絃,因爲他們會比較數字被比較按字典順序給你不正確的輸出,也使用in意味着你會匹配A"Apple"或任何其他地方它不會顯示只是精確匹配,如果你想在一個特定的列來檢查精確匹配,那麼你應該做的正是:

In [8]: cat test.txt 
01,test1,202,290,A,290 
02,test2,303,730,A,0 
03,test3,404,180,N,180 

In [9]: from csv import reader 

In [10]: for row in reader(open("test.txt")): 
      if row[4] == "A" and float(row[3]) > float(row[5]): 
        print(row) 
    ....:   
['02', 'test2', '303', '730', 'A', '0'] 

爲什麼比較數字作爲字符串是一個壞主意:

In [11]: "2" > "1234" 
Out[11]: True 

In [12]: float("2") > float("1234") 
Out[12]: False 
0

你可以試試下面的代碼

for line in open(filename): 
    if 'A' in line: 
     Column=line.split(',') 
     if Column[3] > Column[5]: 
      print Column 
+0

謝謝!這個解決方案很好。 –

+0

@ J.p然後你應該接受答案。 – AlokThakur

0

試試下面的代碼:

from __future__ import print_function 

def condition(cols): 
    return cols[4] == 'A' and cols[3] > cols[5] 

with open('data.txt', 'r') as f: 
    data = f.readlines() 

[print(line) for line in data if condition(line.split(','))] 

您可以在「條件」設置任何邏輯過濾條件功能

+0

這是一個很好的解決方案,但是如何爲每行添加Column [5]和Column [3]之間的區別? –

+0

@ J.p我沒有得到你的問題/評論 - 你想打印列[5]和列[3]之間的區別嗎? – MaxU

+0

是的,對於每條線分開然後也作爲總值(例如對於單獨的線的差值爲290,380,380以及對於每條線的總差值將爲290 + 380 + 380 = 1050)。 –

0

我猜你一定要看看pandas

它會讓一切更容易:

from __future__ import print_function 
import pandas as pd 

df = pd.read_csv('data.txt', names=['col1','col2','col3','col4','col5','col6']) 
print('Given data-set') 
print(df) 

df['diff'] = df['col4'] - df['col6'] 
flt = df[(df.col5 == 'A') & (df.col4 > df.col6)] 
print('Filtered data-set') 
print(flt) 

#print(df.sum(axis=0, numeric_only=True)) 
print('sum(col6) = %d' % (df.sum(axis=0, numeric_only=True)['col6'])) 

輸出:

Given data-set 
    col1 col2 col3 col4 col5 col6 
0  1 test1 202 290 A 290 
1  2 test2 303 730 A  0 
2  3 test3 404 180 N 180 
Filtered data-set 
    col1 col2 col3 col4 col5 col6 diff 
1  2 test2 303 730 A  0 730 
sum(col6) = 470 
相關問題