2014-10-11 36 views
0

我有一個文件有相同/重複的相鄰行(n數),有沒有辦法我可以刪除這些重複的相鄰行形成文件?如何使用python刪除文件中相同的相鄰行/行?

我的文件看起來是這樣的:

Python is good 
python is good 
python is best 
python is best 
python is best 
Best scripting language 
Best scripting language 
Best scripting language 

我期待輸出是這樣的:

Python is good 
python is best 
Best scripting language 

下面是代碼,其中「sample_list」是我創建的列表在我的腳本的前面部分......並且當我用於循環時,我的「newfile」被寫入相同的行(列表「sample_list」中的元素的數目)相鄰的行。所以我試圖消除同相鄰的線

file1 = open(filename, 'r') 
file2 = open('newfile', 'w') 
for line in file1: 
    for s in sample_list: 
     sample = line.replace('better', s) 
     file2.write(sample) 
file1.close() 
file2.close() 
+0

那麼你的代碼在哪裏,它的問題究竟是什麼?這不是一個代碼寫入服務。 – jonrsharpe 2014-10-11 18:00:36

+0

在* nix shell中:'uniq -i uselpa 2014-10-11 18:15:07

回答

0

你可以檢查新sample是否與以前的有所不同:

newSample = line.replace('better', s) 
if newSample.lower() != oldSample.lower(): 
    file2.write(newSample) 
oldSample = newSample 

降低的情況下通過lower()讓你忽略時的情況下的轉換比較字符串。

請注意,我沒有測試過這些代碼行。在進入for-loop之前,您可能需要初始化oldSample