Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中过滤大文件中的重叠行_Python_Overlap - Fatal编程技术网

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

如何在python中过滤大文件中的重叠行,python,overlap,Python,Overlap,我试图用python过滤一个大文件中的重叠行。重叠度设置为25%。也就是说,任意两行相交的元素数小于它们并集的0.25倍。如果大于0.25,则删除一行。因此,如果我有一个总共有10万行的大文件,前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

我试图用python过滤一个大文件中的重叠行。重叠度设置为25%。也就是说,任意两行相交的元素数小于它们并集的0.25倍。如果大于0.25,则删除一行。因此,如果我有一个总共有10万行的大文件,前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,第2行被删除。第3行和第5行也被删除。最终答案是第1行和第4行

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

伪代码如下所示:

结束


如何在python中解决这个问题?谢谢大家!

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

此代码未经测试,但您知道:

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))

因为很明显如何对每行的元素进行排序,我们可以这样做。如果顺序是定制的,我们必须将读取行与每个集合元素耦合,这样我们就可以准确地写回最后读取的行,而不是重新生成它。

亲爱的Lauritz V.Thaulow。上面的代码经过测试,是正确的。现在,这个问题变成了过滤两行和其他两行的重叠。详细信息可以在中找到。如何在python中解决这个问题?非常感谢。亲爱的Lauritz V.Thaulow。另一个问题可以在中找到,我修改此代码以解决该问题,但它是错误的。如何修复它?非常感谢。
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))