gpt4 book ai didi

python - 如何从文件中删除重复的行?

转载 作者:IT老高 更新时间:2023-10-28 22:05:50 33 4
gpt4 key购买 nike

我有一个包含一列的文件。如何删除文件中的重复行?

最佳答案

在 Unix/Linux 上,按照 David Locke 的回答,使用 uniq 命令,或者按照 William Pursell 的评论,使用 sort

如果您需要 Python 脚本:

lines_seen = set() # holds lines already seen
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()

更新: sort/uniq 组合将删除重复项,但返回一个文件,其中行已排序,可能是也可能不是你要。上面的 Python 脚本不会重新排序行,而只是删除重复项。当然,要让上面的脚本也进行排序,只需省略 outfile.write(line) 而是在循环之后立即执行 outfile.writelines(sorted(lines_seen) ).

关于python - 如何从文件中删除重复的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1215208/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com