删除反向重复行的python脚本

2024-03-29 13:52:51 发布

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

我得到了一个python代码,如果行在反转时相似,它会删除行。例如,如果我的文档包含:

1,2 3,4
5,6 7,8
2,1 4,3
5,6 8,7

执行脚本后,输出为

5,6 7,8
2,1 4,3
5,6 8,7

假设一行的第一列为1,2,第二列为7,8,那么,如果另一行的每列包含反转值2,1和8,7,则视为反转。你知道吗

但是,我注意到脚本没有保持行的顺序。排队对我来说很重要。另外,我需要删除第二个类似的反向行,而不是第一个一个。那个代码是

import sys

with open(sys.argv[1]) as inf:

    keys = set()

    for line in inf:

        ports, ips = line.split()

        port1, port2 = ports.split(",")

        ip1, ip2 = ips.split(",")

        if ip1 < ip2:

            keys.add((ip1, port1, ip2, port2))

        else:

            keys.add((ip2, port2, ip1, port1))

with open('results', 'w') as outf:

    for result in keys:

        outf.write("{1},{3}\t{0},{2}\n".format(*result))

有什么想法吗?如果我们能在bash脚本上实现它,有什么建议吗?你知道吗

谢谢


Tags: 代码脚本foraswithsyslineopen
2条回答

您可以在这里使用collections.OrderedDict

>>> from collections import OrderedDict
>>> dic = OrderedDict()
with open('file.txt') as f:
    for line in f:
        key = tuple(tuple(x.split(',')) for x in line.split())
        rev_key = tuple(x[::-1] for x in key)
        if key not in dic and rev_key not in dic:
            dic[key] = line.strip()
...             
>>> for v in dic.itervalues():
    print v
...     
1,2 3,4
5,6 7,8
5,6 8,7

既然你提到了bash,这里有一个awk的解决方案

awk -F'[ ,]' 'BEGIN{OFS=","} {$1=$1};
!($0 in arr){print($1,$2" "$3,$4);arr[$2","$1","$4","$3]}' file.txt

1,2 3,4
5,6 7,8
5,6 8,7

相关问题 更多 >