在模板后用空格拆分字符串

Split a string with whitespaces following a template

我有以下字符串 header(模板):

Port          Name               Status    Vlan      Duplex  Speed   Type

和字符串 str:

Eth1/2        trunk to dg-qwu-29 connected trunk     full    1000    1/10g

如何使用 header,将 str 剥离到以下列表?

[Eth1/2, trunk to dg-qwu-29, connected, trunk, full, 1000, 1/10g]

您没有提供有关列值如何格式化的信息,即分隔符、转义字符和字符串引号。根据您的示例,我会说棘手的部分是名称列,您必须根据排除项提取该列。这是一个快速的方法,您可以从那里开始:

# Get the first element
first = str.split()[0]
# Get the last part of the string, excluding name 
last = str.split()[::-1][0:5]
last = last[::-1]
# Get the name column via exclusion of the two parts previously calculated
middle = str.split(first)[1].split(last[0])[0].strip()
r_tmp = [first, middle]
result = r_tmp + last
print result

以下假定行和 headers 遵循空白掩码。也就是说,header 文本与行列对齐。

import re
header =  "Port          Name               Status    Vlan      Duplex  Speed   Type"
row    =  "Eth1/2        trunk to dg-qwu-29 connected trunk     full    1000    1/10g"
# retrieve indices where each header title begins and ends
matches = [(m.group(0), (m.start(), m.end()-1)) for m in re.finditer(r'\S+', header)]
b,c=zip(*matches)
# each text in the row begins in each header title index and ends at most before the index 
# of the next header title. strip() to remove extra spaces
items = [(row[j[0]:(c[i+1][0] if i < len(c)-1 else len(row))]).strip() for i,j in enumerate(c)]
print items

以上输出:

['Eth1/2', 'trunk to dg-qwu-29', 'connected', 'trunk', 'full', '1000', '1/10g']

编辑:从https://whosebug.com/a/13734572/1847471

检索索引