Python捕获文件解析

2024-04-29 21:04:27 发布

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

我有一个radius捕获文件,我需要解析它。如何获取单个值对并聚合它们。下面是该文件的一个简短片段:

Acct-Session-Id = "1234adb"
Acct-Session-Time = 141312
Acct-Input-Octets = 1234123

这种情况不断重复,结构相同,但价值观不同。你知道吗

我需要聚合八位字节,这很容易,因为我只做"if "Acct-Input-Octets" in结构。你知道吗

如果会话时间变为0(即,它们重新连接),则总数将发生变化。因此,运行总数需要重置,除非它没有重置,在这种情况下这是一个错误(在RADIUS中,输入八位字节必须用新的会话ID重置)。你知道吗


Tags: 文件idinputiftimesession情况结构
2条回答

像这样的?你知道吗

totals = 0
for line in fileObj:
    name, value = line.split('=')
    if name.strip() == 'Acct-Session-Time' and value.strip() == '0':
        totals = 0
    elif name.strip() == 'Acct-Input-Octets':
        totals += int(value.strip())

这里有一个正则表达式方法:

步骤:

1-将时间和八位字节读入两个列表

2-遍历时间并存储“0”元素的最后一个索引,同时检查同一索引中的八位字节,确保它是否也是“0”,如果不是则抛出异常

3-将从“0”的结尾到最后一个索引的值相加(以八位字节为单位)

import re

log = open('log.txt').read()

times = re.findall('Acct-Session-Time\s*=\s*(\d+)\s*', log)
octets = re.findall('Acct-Input-Octets\s*=\s*(\d+)\s*', log)

last_zero_index = 0

for i in range(0, len(times)):
    if times[i] == '0':
        last_zero_index = i
        if octets[i] != '0':
            raise Exception('Session time is reset but the usage is not')

totals = 0

for value in octets[-last_zero_index:]:
    totals += int(value)

print(totals)

相关问题 更多 >