我解析一个文本文件中的以下行。
stp 11441 0 0 0 0
txt 文件中总是出现 2 个这样的行。我正在查找该行中的第二个值(此处为 11441)并将其保存为变量。
我已经弄清楚如何仅使用一个变量进行此类操作。 这是我正在使用的代码
import re
with open('cpu.txt', 'r') as file:
for line in file:
match = re.search('stp \d{2,100}', line)
if match:
stp_queue1 = match.group().split( )[1]
但是,我无法理解如何为第二次匹配发生指定变量(在这种情况下为 stp_queue2
)。
换句话说: 如果文件包含以下 2 行:
stp 11441 0 0 0 0
stp 20000 0 0 0 0
那么 stp_queue1
应分别为 11441,stp_queue2
应分别为 20000。
你能帮我解决这个问题吗?
最佳答案
可以使用多种模式来解决此问题:
我向您展示了三种模式,您可以选择您想要的:
first pattern :
import re
pattern=r'stp\s(\d+)'
output=[]
with open('file.txt','r') as f:
for line in f:
match=re.search(pattern,line)
output.append(match.group(1))
print(output)
输出:
['11441', '20000']
Pattern 2:
r'[0-9]{5}'
pattern 3:
Positive Lookbehind (?<=stp\s)
pattern=r'(?<=stp\s)\d+'
关于python - 如何自动创建第二个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023680/