如何在python中过滤大文件中的重叠行

2024-09-25 18:18:51 发布

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

我正在尝试在中筛选大文件中的重叠行Python重叠度设置为25%。也就是说,任意两行之间的交集元素数小于0.25倍的并集他们。如果大于0.25,一行删除了。所以如果我有一个总共有1000 000行的大文件,前5行如下:

c6 c24 c32 c54 c67
c6 c24 c32 c51 c68 c78
c6 c32 c54 c67
c6 c32 c55 c63 c85 c94 c75
c6 c32 c53 c67

因为第一行和第二行的相交元素数为3(如c6、c24、c32),所以它们之间的并集数为8(如c6、c24、c32、c54、c67、c51、c68、c78)。重叠度为3/8=0.375>;0.25,第二行为已删除销售订单做第三个和第五个行。那个最后答案是第一排和第四排。在

c6 c24 c32 c54 c67
c6 c32 c55 c63 c85 c94 c75

伪代码如下:

for i=1:(n-1)    # n is the number of rows of the big file
    for j=(i+1):n  
        if  overlap degrees of the ith row and jth row is more than 0.25
          delete the jth row from the big file
        end
   end

end

如何用python解决这个问题?谢谢您!在


Tags: 文件ofthe元素endrowc6c32
1条回答
网友
1楼 · 发布于 2024-09-25 18:18:51

棘手的部分是,您必须修改要迭代的列表,同时仍然要跟踪两个索引。一种方法是后退,因为删除索引等于或大于您跟踪的索引的项不会影响它们。在

此代码未经测试,但您会得到这样的想法:

with open("file.txt") as fileobj:
    sets = [set(line.split()) for line in fileobj]
    for first_index in range(len(sets) - 2, -1, -1):
        for second_index in range(len(sets) - 1, first_index, -1):
            union = sets[first_index] | sets[second_index]
            intersection = sets[first_index] & sets[second_index]
            if len(intersection) / float(len(union)) > 0.25:
                del sets[second_index]
with open("output.txt", "w") as fileobj:
    for set_ in sets:
        # order of the set is undefined, so we need to sort each set
        output = " ".join(sorted(set_, key=lambda x: int(x[1:])))
        fileobj.write("{0}\n".format(output))

既然很明显如何对每一行的元素进行排序,我们可以这样做。如果顺序是定制的,那么我们必须将read行与每个set元素耦合起来,这样我们就可以精确地写回最后读取的行,而不是重新生成它。在

相关问题 更多 >