2011-08-26 44 views
1

給出的形式的數據:Python或命令行實用程序 - 排序和過濾文件?

a b 1.1 
c d 2.3 
b a 1.1 

是否有可能基於該thired列進行排序這樣的文件,並刪除其中的第三列中的條目是重複的線條,使得輸出將是:

a b 1.1 
c d 2.3 

,或者

c d 2.3 
b a 1.1 

我能夠僅使用python,R或命令行實用程序在一組非常大的文件上執行此任務。

謝謝!

+1

你如何決定其中的 「1.1」 行放棄? – MattH

+0

丟棄哪個並不重要。 –

回答

8

的Unix sort應該能夠做到爲您的工作:

cat file | sort -u -k3,3n 
a b 1.1 
c d 2.3
cat file | sort -u -k3,3rn 
c d 2.3 
a b 1.1
+0

這有什麼用? – Dominik

+4

@Dominik:它不怎麼幫忙? – sehe

+1

@Dominik:OP顯示了兩個樣本輸出,每個排序方向一個,並且OP已經說過丟棄的重複行並不重要。我想我已經證明了OP的要求。 – MattH

2
f = open('text.txt','rb') 
filter = [] 
rows = [] 
for line in f: 
    line = line.replace('\r\n','') 
    data = line.split(' ') 
    if len(data) >= 3: 
     if not data[2] in filter: 
      filter.append(data[2]) 
      rows.append(data) 
f.close() 

f = open('output.txt','wb') 
for row in rows: 
    f.write(row[0] + ' ' + row[1] + ' ' + row[2] + '\r\n') 
f.close()