1

I have some data that looks likethis, number of lines can vary:

? (192.168.30.4) at 00:10:60:0a:70:26 [ether]  on vlan20                        
? (192.168.30.1) at 70:ca:9b:99:6a:82 [ether]  on vlan20 
#etc similar format

I want to parse this such that I can print something like this in a table:

#Protocol  Address          Age (min)   Hardware Addr   Type   Interface          
#Internet  192.168.30.4             -   0010.600a.7026  ARPA   Vlan20              
#Internet  192.168.30.1             -   70ca.9b99.6a82  ARPA   Vlan20

I split the data by line into two lists

 parse = proc_stdout.split('\n')

This gave a list with two elements:

['? (192.168.30.4) at 00:10:60:0a:70:26 [ether]  on vlan20', '? (192.168.30.1) a
t 70:ca:9b:99:6a:82 [ether]  on vlan20', '']

Now I wish to split the data further so that at each space in a list a new list is created. This would yield a list of lists for each line of the output above. I could then search each list of lists to extract the data I need and print it. However you can't split a list? What's the best way to do this?

4

2 回答 2

2

您可以为此目的使用列表理解或生成器语句:

parse = proc_stdout.strip('\n').split('\n')
parsed_list = [line.split() for line in parse]

或生成器,如果您将结果处理成其他结构

parse = proc_stdout.strip('\n').split('\n')
parsed_list = (line.split() for line in parse)
于 2013-06-13T09:50:19.033 回答
1

您可以strs.splitlines在此处使用和列表理解:

>>> data="""? (192.168.30.4) at 00:10:60:0a:70:26 [ether]  on vlan20                        
... ? (192.168.30.1) at 70:ca:9b:99:6a:82 [ether]  on vlan20"""
>>> [line.split() for line in data.splitlines()]
[['?', '(192.168.30.4)', 'at', '00:10:60:0a:70:26', '[ether]', 'on', 'vlan20'],
 ['?', '(192.168.30.1)', 'at', '70:ca:9b:99:6a:82', '[ether]', 'on', 'vlan20']
]

对于所需的输出,您必须在此处使用字符串格式:

data="""? (192.168.30.4) at 00:10:60:0a:70:26 [ether]  on vlan20                        
? (192.168.30.1) at 70:ca:9b:99:6a:82 [ether]  on vlan20"""

print "#Protocol  Address          Age (min)   Hardware Addr   Type   Interface"  
for line in data.splitlines():
    _,ip,_,har_ad,_,_,interface = line.split()
    ip = ip.strip('()')
    it = iter(har_ad.split(':'))
    har_ad = ".".join([x+y for x,y in zip(it,it)])
    print "#Internet  {} {:>11s} {:>18s} {:>5s} {:>8s}".format(ip,'-', har_ad,'ARPA' ,interface)        

输出:

#Protocol  Address          Age (min)   Hardware Addr   Type   Interface
#Internet  192.168.30.4           -     0010.600a.7026  ARPA   vlan20
#Internet  192.168.30.1           -     70ca.9b99.6a82  ARPA   vlan20
于 2013-06-13T10:04:01.667 回答