使用Python删除txt文件中重复行和特定字符串行的最快方法是什么?

6 投票
3 回答
2226 浏览
提问于 2025-04-16 05:54

这个文本大约有22000行,大小大约是3.5MB。里面有很多重复的行。我想要做的就是去掉这些重复的行,还有一些包含特定字符串的行,这些行我不需要。

我处理的方式是先用readlines()方法把文件读进一个大列表,然后再用read()方法把文件作为一个大字符串读进来。接着我遍历这个列表,统计每一行出现的次数,把重复的行替换成空字符串。结果我花了10分钟就完成了这个工作?!

有没有更快的方法来做到这一点呢?

非常感谢!

3 个回答

0
goodLines = set()
badString = 'bad string'

with open(inFilename, 'r') as f:
    for line in f:
        if badString not in line:
            goodLines.add(line)

# and let's output these lines (sorted, unique) in another file...

with open(outFilename, 'w') as f:
    f.writelines(sorted(goodLines))

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

3
list(set(line for line in file.readlines()
         if 'badstring' not in line
         and 'garbage' not in line))

另外,使用正则表达式可能比多个 not in 测试要快。

3

我几乎总是使用生成器来处理文件。这种方式让代码运行得快,修改起来简单,而且测试也方便。

首先,创建一个生成器,用来去除重复的内容:

def remove_duplicates(seq):
    found = set()
    for item in seq:
        if item in found:
            continue
        found.add(item)
        yield item

这个有效吗?

>>> print "\n".join(remove_duplicates(["aa", "bb", "cc", "aa"]))
aa
bb
cc

看起来是有效的。接下来,创建一个函数,用来判断一行内容是否合格:

def is_line_ok(line):
    if "bad text1" in line:
        return False
    if "bad text2" in line:
        return False
    return True

这个有效吗?

>>> is_line_ok("this line contains bad text2.")
False
>>> is_line_ok("this line's ok.")
True
>>> 

现在我们可以把 remove_duplicatesitertools.ifilter 结合我们的函数使用了:

>>> seq = ["OK", "bad text2", "OK", "Also OK"]
>>> print "\n".join(remove_duplicates(ifilter(is_line_ok, seq)))
OK
Also OK

这种方法可以用于任何返回字符串的可迭代对象,包括文件:

with open(input_file, 'r') as f_in:
    with open(output_file, 'w') as f_out:
       f_out.writelines(remove_duplicates(ifilter(is_line_ok, f_in)))

撰写回答