Skip to main content
 首页 » 编程设计

Python之如何匹配文本文件中多行的特定单词/数字并将它们存储在单独的列表中

2025年05月04日14del

我有一个 .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]=3553
mpid[0]=6553 和 mpid[1]=7553
vlan[0]=2553 和 vlan[1]=3553
tag[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] ?

如果可能的话,我还想要一些解释。

谢谢。

请您参考如下方法:

解释你想要的正则表达式及其工作原理

上述所有答案都有效,但如果您想真正了解问题,我认为这可能是一个不错的方法。首先,您需要考虑要查找的内容。

对于前三个,您希望匹配类似于 name space digits 的模式。正则表达式是 name\d+ \d 表示一个数字字符,+ 表示一个或多个。

所以对于 ip sla 你会想要一个像这样的正则表达式:

ip sla \d+ 

但是你只对数字感兴趣,所以你可以使用括号将数字指定为它自己的组:

ip sla (\d+) 

最后,在 python 中,反斜杠 (\) 用于转义它前面的字符,所以为了让 python 识别你的反斜杠,我们需要两个反斜杠,所以在 python 代码中你会有:

pattern = "ip sla (\\d+)" 

如果你看the docs , re 模块有一个函数 re.findall 使你不必将文件分成几行。

re.findall(pattern, string) 将返回匹配模式的字符串列表,或者如果只有一组存在(就像在我们的情况下,一组是 \d+) 它将返回该组。

也就是说

re.findall("ip sla (\\d+)", fileText) 

将返回作为您的 ip sla 值的数字列表(作为字符串)。

同样适用于mpid和vlan。

但是,对于标签,您希望匹配字母和数字。在正则表达式中,这些被称为单词字符,我们可以使用 \w 来匹配单词字符。我们将再次使用 + 修饰符来匹配一个或多个单词字符。这给我们留下了

pattern = "tag (\\w+)" 

策略:

1. Read file into string 
 
2. Construct and execute regex searches for each pattern 
 
3. Iterate through each list of results 
 
4. Append each result to the correct array 

代码:

import re 
 
myFile = open("regex.txt","r")  # open file for reading 
myFileData = myFile.read()      # read file into a string 
myFile.close()                  # close file now that we're done 
 
# create lists for each thing you're looking for 
ipsla = [] 
mpid = [] 
vlan = [] 
tag = [] 
 
# finds a pattern like "ip sla <one or more digits 0-9>" 
results = re.findall("ip sla (\\d+)", myFileData) 
for result in results: 
        # add the number (as an int) to your ipsla list 
        ipsla.append(int(result)) 
 
# rinse & repeat :) 
results = re.findall("mpid (\\d+)", myFileData) 
for result in results: 
        mpid.append(int(result)) 
 
results = re.findall("vlan (\\d+)", myFileData) 
for result in results: 
        vlan.append(int(result)) 
 
results = re.findall("tag (\\w+)", myFileData) 
for result in results: 
        if result not in tag: 
                tag.append(result) 
 
print ipsla 
print mpid 
print vlan 
print tag