【发布时间】:2015-02-20 21:24:22
【问题描述】:
我有一个 .txt 文件,它是这样的:
ip sla logging traps
ip sla 2553
ethernet jitter mpid 6553 domain Gravity vlan 2553 num-frames 100 interval 100
tag CSCO5839
frequency 300
ip sla schedule 2553 life forever start-time now
ip sla 3553
ethernet jitter mpid 7553 domain Gravity vlan 3553 num-frames 100 interval 100
tag CSCO5839
frequency 300
ip sla schedule 3553 life forever start-time now
我想要一种方法来匹配 ip sla / mpid / vlan 和标记并将它们的值存储到列表或向量中:
期望的输出:
ipsla[0]=2553 和 ipsla[1]=3553mpid[0]=6553 和 mpid[1]=7553vlan[0]=2553 和 vlan[1]=3553tag[0]=CSCO5839
现在,我刚开始学习 Python,我知道我必须解析文件的每一行,然后使用 re.match() 匹配所需的结果,然后将获得的结果存储在数组或列表中。
到目前为止我的代码很糟糕:
#!/usr/bin/env python
import re
myFile = open("regex.txt","r")
for line in myFile:
if re.match("",line): #I should have a condition there but I got lost
#now I have to store that variable in an array / or a list
到目前为止我的问题:
- 我应该使用什么表达才能找到我需要的东西?
- 那么,我怎样才能将这些值存储在同名的向量/列表中?例如:ipsla[0]、ipsla[1]?
如果可能的话,我也想要一些解释。
谢谢。
【问题讨论】:
-
您可以查看docs.python.org/2/library/re.html 以了解有关 Python 正则表达式的更多信息。列表可以声明为空,然后可以将对象附加到它们,请参阅tutorialspoint.com/python/python_lists.htm。
标签: python regex string python-2.7