Python 将具有可变参数数的数据帧拆分为元组
我有一本运行命令的ansible剧本Python 将具有可变参数数的数据帧拆分为元组,python,Python,我有一本运行命令的ansible剧本 #show int status 在网络设备上。我正在计算可用的可用端口数。它返回这个输出 [u'Et2 description1 notconnect in Po23 full 10G Not Present '] [u'Et3 description2 notconnect 1152 full 10G Not Present '] [u'Et4
#show int status
在网络设备上。我正在计算可用的可用端口数。它返回这个输出
[u'Et2 description1 notconnect in Po23 full 10G Not Present ']
[u'Et3 description2 notconnect 1152 full 10G Not Present ']
[u'Et4 other desc notconnect 1 full 10G Not Present ']
[u'Et5 notconnect 1 full 10G Not Present ']
我只对前三个专栏感兴趣。网络设备不支持json格式,因此无法运行
#show int status | json
我想有3个列表,然后我可以压缩并使用,就像我已经为其他支持json的网络设备所做的那样;名单看起来像
list1 = ['Et2', 'Et3', 'Et4', 'Et5']
list2 = ['description1', 'description2', '', '']
list3 = ['notconnect','notconnect', 'notconnect', 'notconnect']
但是由于description字段有时是空的,因此我无法找到一个好的.split()来准确地返回列表,因为.split[1]有时会有一个描述,如果按间距拆分,有时会是'notconnect'。有没有一种好的方法可以做到这一点?正则表达式可能是最好的解决方案,但无论如何,如果您不想使用它,我看到了两种解决方案 第一:使用这样一个事实:行之间的格式似乎相当一致,并且每个新项都从行中的同一点开始
a = 'Et3 description2 notconnect 1152 full 10G Not Present '
b = 'Et4 notconnect 1 full 10G Not Present '
L = [a, b]
list1, list2, list3 = [], [], []
for elt in L:
list1.append(elt[0:11].strip(" "))
list2.append(elt[11:30].strip(" "))
list3.append(elt[30:43].strip(" "))
# Output:
list1
Out[8]: ['Et3', 'Et4']
list2
Out[9]: ['description2', '']
list3
Out[10]: ['notconnect', 'notconnect']
其次,在elt:语句中使用if/elif“string”并构建规则来解析数据
使用rstrip()进行编辑:
你试过使用正则表达式吗?@Arnaud regex对我来说绝对是一个弱点不幸的是,它是notconnect common和everypresent,或者它可以是此字段中的其他值吗?如果是,那么哪个值(我假设是连接?)@Mathieu connected、notconnected、disabled、err disabled是潜在状态如果您对所有潜在状态都有一个非常精确的预期,那么我猜我们可以找出一个正则表达式。前两列是“Et*”和“description*”,总是更新了问题道歉,没有意识到有些描述在字符串中有空格,只是用rstrip(“”)替换strip(“”)就行了。重点是,您要分析的elt是从同一个ID开始的。我们不关心它们在哪一个结束,只删除结尾处的空格。
a = 'Et3 description2 notconnect 1152 full 10G Not Present '
b = 'Et4 other desc notconnect 1 full 10G Not Present '
L = [a, b]
list1, list2, list3 = [], [], []
for elt in L:
list1.append(elt[0:11].rstrip(" "))
list2.append(elt[11:30].rstrip(" "))
list3.append(elt[30:43].rstrip(" "))
# Output
list1
Out[2]: ['Et3', 'Et4']
list2
Out[3]: ['description2', 'other desc']
list3
Out[4]: ['notconnect', 'notconnect']