如何在python中检查逆序字符串元组并从文件中消除它们?

2024-04-20 08:19:05 发布

您现在位置: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")

有人能帮我吗?你知道吗


Tags: intxtforoutputdatavalueaswith
1条回答
网友
1楼 · 发布于 2024-04-20 08:19:05

看到您的代码有一个单一文件的列表,我假设您正在将其泛化为处理多个文件。在这种情况下,您没有提到某些内容,您希望这些组合在文件中保持不变吗?你已经接近你的实现了。您可以使用更简单的结构set和get O(1)search,而不是使用字典来获取O(1)search。你知道吗

持久覆盖文件列表

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()的位置

相关问题 更多 >