【问题标题】:How to : python string parsing with whitespaces, except single space between words?如何:用空格解析python字符串,除了单词之间的单个空格?
【发布时间】:2016-04-16 07:05:33
【问题描述】:

一直致力于解析 iptables 输出以使用 python 获取每个源 IP 的统计信息。不想包含 iptc 模块。 所以只是做字符串操作。

bytes target     prot opt in     out     source               destination         
        0     0            udp  --  *      eth1    10.10.10.10          0.0.0.0/0           udp spt:10 
        0     0            tcp  --  *      eth1    10.10.10.10          0.0.0.0/0           tcp spt:10 
        0     0            all  --  *      eth1    1.1.1.1              0.0.0.0/0           
        0     0            all  --  *      eth1    0.0.0.0/0            0.0.0.0/0           source IP range 5.5.5.5-5.5.5.10 
        0     0            all  --  *      eth1    0.0.0.0/0            0.0.0.0/0           source IP range 4.4.4.4-4.4.4.5 
        0     0            all  --  *      eth1    0.0.0.0/0            0.0.0.0/0          

>>> s='    0     0            udp  --  *      eth1    10.10.10.10          0.0.0.0/0           udp spt:10 '
>>> s.split()
['0', '0', 'udp', '--', '*', 'eth1', '10.10.10.10', '0.0.0.0/0', 'udp', 'spt:10']

想要解析如下,除了单词之间的单个空格外,如何分隔所有空格?

expected_output=['0', '0', 'udp', '--', '*', 'eth1', '10.10.10.10', '0.0.0.0/0', 'udp spt:10']

或者有没有更好的方法从 iptables 获取统计信息,但没有 iptc?

【问题讨论】:

  • 你可以使用re.split:re.split(' {2,}', s)。不过不知道有没有更好的解决方案。
  • 您确定这些块不是制表符分隔的吗?如果是这样,您可以毫无问题地使用s.split('\t')
  • 它的输出“iptables -t -nvL”,

标签: python string iptables


【解决方案1】:

对于 iptables 输出,不能保证所有列都被多个空格分隔。它只是保证至少有一个空格。以下是该命令输出的 sn-p(在我的一台机器上运行时),您可以看到这种情况:

 $> iptables -nvL
 ...
     0     0 ACCEPT     all  --  docker0 docker0  0.0.0.0/0            0.0.0.0/0           
 ...

幸运的是,前 9 列中的值不会有任何空格。因此,您可以对每一行执行以下操作,以按照您想要的方式获取数据:

fs = s.split()
if len(fs) > 9:
     fs[9] = " ".join(fs[9:])
     fs = fs[:10]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 2020-05-18
    • 2015-02-08
    • 1970-01-01
    • 2011-04-28
    • 2018-04-24
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多