从文本文件中删除多个重复行的问题

2024-10-01 00:28:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从文本文件中删除重复的行,并一直面临问题。。。输出文件一直将前两个帐户放在同一行上。每个帐户应有不同的行。。。有人知道为什么会发生这种情况以及如何解决吗

with open('accounts.txt', 'r') as f:
    unique_lines = set(f.readlines())
with open('accounts_No_Dup.txt', 'w') as f:
    f.writelines(unique_lines)

accounts.txt:

@account1
@account2
@account3
@account4
@account5
@account6
@account7
@account5
@account8
@account4

帐户\u No\u Dup.txt:

@account4@account3
@account4
@account8
@account5
@account7
@account1
@account2
@account6

打印(唯一行)

{'@account4', '@account7\n', '@account3\n', '@account6\n', '@account5\n', '@account8\n', '@account4\n', '@account2\n', '@account1\n'}

Tags: txtaswith帐户openuniqueaccountsaccount2
3条回答

您的问题是set会更改行的顺序,并且最后一个元素不会以\n结尾,因为文件末尾没有空行

只需添加分隔符,或者不使用set

with open('accounts.txt', 'r') as f:
    unique_lines = set()
    for line in f.readlines():
        if not line.endswith('\n'):
            line += '\n'
        unique_lines.add(line)


with open('accounts_No_Dup.txt', 'w') as f:
    f.writelines(unique_lines)

您可以使用unique关键字轻松地完成它

代码如下

import pandas as pd

data = pd.read_csv('d:\\test.txt', sep="/n", header=None)
df =  pd.DataFrame(data[0].unique())

with open('d:\\testnew.txt', 'a') as f:
    f.write(df.to_string(header = False, index = False)))

结果:要读取的测试文件包含数据

enter image description here

结果是它删除了重复的行

enter image description here

文件中的最后一行缺少换行符(从技术上讲,这是对POSIX standards for text files的违反,但您必须对此加以说明),因此前面的"@account4\n"被解释为相对于末尾的"@account4"是唯一的。我建议无条件地剥离换行符,并在编写时重新添加它们:

with open('accounts.txt', 'r') as f:
    unique_lines = {line.rstrip("\r\n") for line in f}  # Remove newlines for consistent deduplication
with open('accounts_No_Dup.txt', 'w') as f:
    f.writelines(f'{line}\n' for line in unique_lines)  # Add newlines back

顺便说一句,在现代Python上(对于任何解释器,CPython/pypy3.6+,3.7+),您可以通过使用dict而不是set来保持第一次出现的顺序。只需将文件的读取更改为:

    unique_lines = {line.rstrip("\r\n"): None for line in f}

您将在第一次看到每一行时看到它,以该顺序显示,随后的重复项将被忽略

相关问题 更多 >