我有一个类似输出的表格,我想从按列分隔的每一行获取输入。 不幸的是,列并不总是具有相同的宽度,并且列内可能有空格。 但该列始终从标题中描述的位置开始,到下一个标题之前的 1 个字段结束。 我的想法是获取标题中单词的位置,然后用类似的内容分割线
var = 行[第一个字:第二个字-1] var2 = 行[第二个字:第三个字-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相反。
关于Python 从标题中获取列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45343131/