【问题标题】:Delete in Python duplicate reverse strings from a text file在 Python 中从文本文件中删除重复的反向字符串
【发布时间】:2021-12-04 09:34:50
【问题描述】:

我有这个文件(有数千行)。每行包含两个用空格分隔的数字:

3466    937
3466    5233
3466    8579
3466    10310
3466    15931
3466    17038
3466    18720
3466    19607
10310   1854
10310   3466
10310   4583
10310   5233
10310   9572
10310   10841
10310   13056
10310   14982
10310   16310

我必须删除在 python 中以相反顺序重复的行,即 10310 3466 和 3466 10310 应该只显示为一行(10310 3466 或 3466 10310)。有任何想法吗? 谢谢。

【问题讨论】:

    标签: python string text duplicates reverse


    【解决方案1】:

    一种方法是使用frozenset 生成不区分顺序的密钥:

    # change data.csv to the name of your file
    with open("data.csv") as infile:
        uniques = set(frozenset(line.strip().split()) for line in infile)
        for value in uniques:
            print(*value)
    

    输出 (对于给定的输入)

    10310 3466
    5233 10310
    10310 4583
    19607 3466
    1854 10310
    3466 8579
    10310 9572
    10310 13056
    10310 14982
    5233 3466
    17038 3466
    15931 3466
    10310 10841
    937 3466
    18720 3466
    16310 10310
    

    替代方案,使用sorted将每一行转换为相同的key:

    # change data.csv to the name of your file
    with open("data.csv") as infile:
        uniques = set(" ".join(sorted(line.strip().split())) for line in infile)
        for value in uniques:
            print(value)
    

    为了更好地理解使用frozenset 的方法,请参见下面的代码:

    frozenset((1, 2)) == frozenset((2, 1))
    Out[2]: True
    

    可以看出,两个frozenset 相等,与用作输入的元组的顺序无关。常规集也会发生这种情况,但frozensets是可散列的,来自文档:

    frozenset 类型是不可变和可散列的——它的内容不能 创建后更改;因此它可以用作字典 键或作为另一个集合的元素。

    注意

    要将重复数据删除的行写入新文件,请执行以下操作:

    # change data.csv to the name of your file
    with open("data.csv") as infile:
        uniques = set(frozenset(line.strip().split()) for line in infile)
    
        # change output.csv to the name of your output file
        with open("output.csv", mode="w") as outfile:
            for value in uniques:
                outfile.write(f'{" ".join(value)}\n')
    

    【讨论】:

    • 非常感谢!我需要添加什么来覆盖文件,以便它包含上面打印的值?
    • 您可以将其写入新文件
    • @kiter23 更新了答案
    【解决方案2】:

    似乎数字的顺序并不重要,所以你可以这样做:

    filename='data.txt'
    
    list=[]
    
    with open(filename) as file:
        lines = file.readlines()
        for line in lines:
            nums=line.split(' ')
            nums = ' '.join(nums).split()
            a,b=int(nums[0]),int(nums[1])
            min=a
            max=b
            if b<a:
                min=b
                max=a
            list.append(str(min)+' '+str(max))
    
    uniqueSet=set(list)
    with open("output.txt", mode="w") as outfile:
        for l in uniqueSet:
            outfile.write(l+'\n')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 2016-07-13
      • 2014-12-19
      • 2018-03-21
      相关资源
      最近更新 更多