【问题标题】:Remove both duplicates (original and duplicate) from text file using python使用python从文本文件中删除重复项(原始和重复)
【发布时间】:2021-04-09 01:24:49
【问题描述】:

我尝试删除两个重复项,例如:

STANGHOLMEN_TA02_GT11
STANGHOLMEN_TA02_GT41
STANGHOLMEN_TA02_GT81
STANGHOLMEN_TA02_GT11
STANGHOLMEN_TA02_GT81

结果

STANGHOLMEN_TA02_GT41

我试过这个脚本

lines_seen = set() 
with open(example.txt, "w") as output_file:
    for each_line in open(example2.txt, "r"):
        if each_line not in lines_seen: 
            output_file.write(each_line)
            lines_seen.add(each_line)

但不幸的是,它不能按我的意愿工作,它会丢失行并且不会删除行。原始文件的行之间不时有空格

【问题讨论】:

    标签: python python-3.x string file filtering


    【解决方案1】:

    您需要执行 2 遍才能使其正常工作。因为通过 1 次,您将不知道当前行是否会在以后重复。你应该尝试这样的事情:

    # count each line occurances
    lines_count = {}
    for each_line in open('example2.txt', "r"):
        lines_count[each_line] = lines_count.get(each_line, 0) + 1
    
    # write only the lines that are not repeated
    with open('example.txt', "w") as output_file:
        for each_line, count in lines_count.items():
            if count == 1:
                output_file.write(each_line)
    

    【讨论】:

    • @Chris 很高兴它对你有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2015-01-03
    • 2013-12-13
    相关资源
    最近更新 更多