如何自动创建第二个var?

2024-05-14 23:52:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我为下面一行分析一个文本文件。你知道吗

污水处理厂11441 0 0

在txt文件中总是有两个这样的行出现。我正在查找行中的第二个值(这里是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)。你知道吗

换句话说: 如果文件包含以下两行:

stp 11441 0 0 0 0
stp 20000 0 0 0 0

stp_queue1应分别为11441和stp_queue2应分别为20000。你知道吗

你能帮我一下吗?你知道吗


Tags: 文件代码importretxtmatchwithline
3条回答

您可以将值添加到字典中,而不是每个值都添加到自己的变量中。请参阅下面的代码,将每个匹配项添加到一个字典中,其中键为stp#u queue,数字从1开始。你知道吗

import re
dictionary={}
with open('cpu.txt', 'r') as file:
    counter=1
    for line in file:
        match = re.search('stp               \d{2,100}', line)
        if match:
           dictionary["stp_queue"+str(counter)]  = match.group().split( )[1]
           counter++
print dictionary  

然后要提取数据dictionary["stp_queue1"]将返回为找到的第一个匹配项存储的值。你知道吗

更多关于字典的信息:https://docs.python.org/2/tutorial/datastructures.html#dictionaries

有许多模式可用于解决此问题:

我给你展示了三种模式,你可以选择你想要的:

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+'

如果你把它们放在一个列表中,顺序会被保留,查找起来就像stp_queue[0]一样简单

import re
stp_queue = []
with open('cpu.txt', 'r') as file:
    for line in file:
        match = re.search('stp               \d{2,100}', line)
        if match:
            stp_queue.append(match.group().split( )[1])

相关问题 更多 >

    热门问题