Skip to main content
 首页 » 编程设计

Python从标题中获取列宽

2024年10月01日14oomusou

我有一个类似输出的表格,我想从按列分隔的每一行中获取输入。 不幸的是,该列并不总是具有相同的宽度,并且列内可能有空格。 但是该列始终从标题中描述的位置开始,并在下一个标题之前的 1 个字段结束。 我的想法是获取标题中单词的位置,然后用类似

var = line[firstword:secondword-1] var2 = line[secodword:thirdword-1]

Port      Name           Status    Vlan      Duplex  Speed   Type 
Eth1/1    Server1        connected 1         full    10G     10Gbase-SR  
Eth1/2    Server 2       notconnec 1234      full    10G     SFP-1000BAS 
Eth1/3    That is poss   err-disab trunk     full    10G     10Gbase-SR 

我怎样才能得到这个职位?

请您参考如下方法:

如果您知道列标题,您可以这样做(假设变量 lines 包含表格:

indices = [lines[0].index(header) for header in ["Port", "Name", "Status", "Vlan", "Duplex", "Speed", "Type"]] 

如果不这样做,则假设 header 不包含空格(类似于 Karmanya Aggarwal 已经建议的那样):

indices = [lines[0].index(header) for header in [w for w in lines[0].split(" ") if w != ""]] 

或者使用正则表达式:indices = [lines[0].index(header) for header in [w for w in re.split(r"\s+", lines[0])]]

现在您可以使用索引获取列值:

lines[1][indices[1]:indices[2]].strip() 
# -> Server1 

当然,如果表格实际上是制表符分隔的,您会希望使用 csv module相反。