我有一个相同/重复的相邻行(n号)的文件,有没有办法可以从文件中删除这些重复的相邻行?
我的文件看起来像这样:
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 :(得分:0)
您可以检查新sample
是否与前一个不同:
newSample = line.replace('better', s)
if newSample.lower() != oldSample.lower():
file2.write(newSample)
oldSample = newSample
通过lower()
转换为小写,可以忽略比较字符串的情况。
请注意,我还没有测试过这些代码行。在进入for循环之前,您可能需要初始化oldSample
。