首页 > 解决方案 > 如何检查倒序字符串元组并将它们从 python 文件中删除?

问题描述

我想从我的大文本文件(>16M 行)中删除倒序字符串元组。

例如,如果我的文件中有以下两行:

352_0F, 352_1F,  0.913
352_1F, 352_0F,  0.913

预期的输出将保留这些行中的任何一条(而不是两者):

352_0F, 352_1F,  0.913

col3仅供参考:对于元组及其倒序元组,第三列将是相同的。

我尝试了以下代码,但它没有按预期工作。

from collections import defaultdict
data = defaultdict(list)

with open("OUTPUT.txt","w") as output:
    for fileName in ["Large_INPUT.txt"]:
        with open(fileName,'r') as file1:
            for line in file1:
                col1,col2,value = line.split(",")
                if (col1,col2) not in data:
                     if (col2,col1) not in data:
                         data[(col1,col2,value)]
                         output.write(f"{col1},{col2} {value}\n")

有人可以帮我吗?

标签: python

解决方案


看到您的代码有一个单个文件的列表,我假设您正在将其概括为与多个文件一起使用。在那种情况下,您没有提及某些内容,您是否希望组合在文件中持续存在?你已经接近你的实施了。除了使用字典来获得 O(1) 搜索,您还可以使用更简单的结构、set 并获得 O(1) 搜索。

持久化文件列表

found_combinations = set()
with open("OUTPUT.txt", "w") as output:
    for fileName in ["Large_INPUT.txt"]:
        with open(fileName, 'r') as file1:
            for line in file1:
                cols = [col.strip() for col in line.strip().split(',')]
                new_combination = frozenset(cols)
                if new_combination not in found_combinations:
                    found_combinations.add(new_combination)
                    out = ', '.join(cols) + '\n'
                    output.write(out)

对文件不持久

with open("OUTPUT.txt", "w") as output:
    for fileName in ["Large_INPUT.txt"]:
        found_combinations = set()
        with open(fileName, 'r') as file1:
            for line in file1:
                cols = [col.strip() for col in line.strip().split(',')]
                new_combination = frozenset(cols)
                if new_combination not in found_combinations:
                    found_combinations.add(new_combination)
                    out = ', '.join(cols) + '\n'
                    output.write(out)

请注意,两个版本之间的唯一区别是found_combinations = set()


推荐阅读