2016-03-19 63 views
0

我有一個文件,下面是它的外觀片段。我有這些關聯的分數的話。我怎樣才能刪除有較低分數的副本。我的意思是'新鮮'有兩個分數(7.781和5.750),我試圖用較低的分數去除'新鮮'和其他重複的詞條。這可能嗎?如何從文本文件中刪除重複條目?

['norwegian', 7.781341354126479] 
['rp', 7.7802465301013] 
['fresh', 7.7721646246757885] 
['tick', 7.7721646246757885] 
['wood', 7.7721646246757885] 
['fresh', 5.750711529372451] 
['tick', 4.750711529372451] 

我已經嘗試做以下操作,將文件放到字典中,並將單詞和分數分開。

from collections import defaultdict 
d={} 
last_seen=set() 
with open("scored.txt","r") as filer: 

    for line in filer: 
      term, score= line.strip().split(",",1) 
      if line not in last_seen: 
        last_seen.add(line) 
+0

你的代碼在哪裏? – Vader

+0

你的文件是否包含括號和逗號?另外,請發佈您嘗試過的代碼。 – mhawke

+0

已添加。是的,該文件與上面顯示的格式完全相同。 – minks

回答

3

在你的文本文件中存儲了python列表格式的字符串。您需要ast.literal_eval將字符串表示形式轉換爲列表。和簡單的dict來存儲團隊的分數。試試下面的代碼

import ast 
d={} 
with open("scored.txt","r") as filer: 
    for line in filer: 
      data = ast.literal_eval(line) 
      team,score = data[0],data[1] 
      if team not in d or d[team] < score: 
       d[team] = score 

UPDATE
只需寫入隊組件文件,你可以使用

with open("ofile.txt","w") as f: 
    for team in d: 
     f.write(team) 

這個片段會寫所有球隊的名字隨機順序文件。要保持初始秩序,您應該使用OrderedDictcollections

import ast 
from collections import OrderedDict 
d=OrderedDict() 
... 
# the same code 
+0

如果我想將團隊組件寫入輸出文件,我該怎麼做? with open(「ofile.txt」,「w」)as t: for x in d [0]: print >> t,x – minks

+0

@minks請參閱更新 – kvorobiev

+0

我似乎注意到訂單不是被保存。關鍵是我已經對這些術語進行了排名。刪除重複項時,順序是隨機的。是否有可能將它們保持與以前相同的順序,因爲我只需要它們按排名順序排列? – minks