
在日常系统维护或数据分析中,我们经常需要从大量的日志文件或报告中提取特定信息。这些文件可能分散在不同的子目录中,且内部结构具有一定的规律性。本教程将以一个具体的案例为例,展示如何使用python高效地递归查找、读取并解析这类结构化文本文件中的性能数据,例如网络下载和上传速度。
我们的目标是从以下类型的.txt文件中提取下载和上传速度信息:
> this is first output and some another contents these are some test lines to fill the file Testing download speed Download: 0.00 Mbit/s Testing upload speed Upload: 0.00 Mbit/s > this is second output but other texts go here too these are some test lines to fill the file Testing download speed Download: 1200.58 Mbit/s Upload: 857.25 Kbit/s
每个文件都包含两个主要部分,由>>分隔(尽管示例中是单个>,但核心思想是文件内容被逻辑上分割)。每个部分都有固定数量的行(例如8行),并且下载速度信息位于倒数第三行,上传速度信息位于倒数第一行。我们需要根据速度值和单位(Mbit/s 或 Kbit/s)进行条件判断和格式化输出。
为了高效处理这类任务,我们将采用以下步骤:
首先,我们需要定位所有目标文件。pathlib库提供了简洁的路径操作功能,包括递归查找。
立即学习“Python免费学习笔记(深入)”;
from pathlib import Path
# 定义每个部分的行数和文件包含的逻辑部分数
LINES_PER_PART = 8
PARTS_PER_FILE = 2
def main():
# 递归查找当前目录及其子目录下的所有 .txt 文件
target_files = list(Path(".").rglob("*.txt"))
for filename in target_files:
with open(filename, 'r') as file:
lines = file.readlines()
# ... 后续处理 ...Path(".").rglob("*.txt")会返回一个生成器,遍历当前目录及其所有子目录中符合*.txt模式的文件路径。我们将其转换为列表以便后续迭代。
由于每个文件都由固定行数的逻辑部分组成,我们可以编写一个辅助函数将文件内容(行列表)按指定大小分块。
def chunks(arr, chunk_size):
"""
将列表分成指定大小的块。
Args:
arr (list): 待分块的列表。
chunk_size (int): 每个块的大小。
Returns:
list: 包含所有块的列表。
"""
result = []
for i in range(0, len(arr), chunk_size):
result.append(arr[i:i+chunk_size])
return result在main函数中,读取文件所有行后,即可调用此函数进行分块:
lines = file.readlines()
parts = chunks(lines, LINES_PER_PART)
for i, part in enumerate(parts, 1):
# ... 处理每个部分 ...enumerate(parts, 1)用于在遍历每个部分时,为其分配一个从1开始的序号(例如 Download1, Download2)。
每个部分的下载和上传速度信息都位于特定的行。我们需要一个函数来解析这些行,提取数值和单位。
def parse_speed_info(line_string):
"""
从速度信息字符串中解析出速度数值和单位。
例如:"Download: 1200.58 Mbit/s" -> (1200.58, "Mbit/s")
Args:
line_string (str): 包含速度信息的字符串。
Returns:
tuple: 包含速度浮点值和单位字符串的元组。
"""
# 使用 split() 分割字符串,[1::] 跳过第一个元素(如 "Download:" 或 "Upload:")
speed_info_list = line_string.split()[1::]
return (
float(speed_info_list[0]), # 速度值
speed_info_list[1].strip() # 单位,并去除可能的空白字符
)在main函数中,根据文件结构,下载速度信息在当前块的倒数第三行,上传速度信息在倒数第一行:
download_info = parse_speed_info(part[-3])
upload_info = parse_speed_info(part[-1])根据需求,输出格式需要根据速度值进行条件判断:
def stringify_speed_info(speed, unit):
"""
根据速度值和单位格式化输出字符串。
Args:
speed (float): 速度数值。
unit (str): 速度单位。
Returns:
str: 格式化后的速度信息字符串。
"""
if speed == 0:
return "zero"
elif unit == "Mbit/s" and speed < 600.0: # 假设小于600的条件只针对Mbit/s
return f"less than 600 {unit}"
return f"{speed} {unit}"在main函数中,结合之前解析的信息和当前部分的序号进行打印:
print(f"Download{i} speed of {filename} is {stringify_speed_info(*download_info)}.")
print(f"Upload{i} speed of {filename} is {stringify_speed_info(*upload_info)}.")
print() # 每处理完一个文件的一个部分后打印空行,提高可读性*download_info是一个解包操作,它将元组(speed, unit)作为单独的参数传递给stringify_speed_info函数。
将上述所有部分整合,形成一个完整的Python脚本:
#!/usr/bin/python3
from pathlib import Path
# 定义常量:每个逻辑部分的行数和文件包含的逻辑部分数
LINES_PER_PART = 8
PARTS_PER_FILE = 2
def main():
"""
主函数,执行文件查找、读取、解析和输出的整个流程。
"""
# 递归查找当前目录及其子目录下的所有 .txt 文件
target_files = list(Path(".").rglob("*.txt"))
for filename in target_files:
with open(filename, 'r') as file:
lines = file.readlines()
# 将文件内容按预定义的行数分块
parts = chunks(lines, LINES_PER_PART)
# 遍历每个逻辑部分,提取并打印速度信息
for i, part in enumerate(parts, 1):
# 下载速度信息位于当前部分的倒数第三行
download_info = parse_speed_info(part[-3])
# 上传速度信息位于当前部分的倒数第一行
upload_info = parse_speed_info(part[-1])
# 格式化并打印下载速度信息
print(f"Download{i} speed of {filename} is {stringify_speed_info(*download_info)}.")
# 格式化并打印上传速度信息
print(f"Upload{i} speed of {filename} is {stringify_speed_info(*upload_info)}.")
print() # 每处理完一个文件的某个部分后打印一个空行,增强输出可读性
def chunks(arr, chunk_size):
"""
将一个列表(例如文件行列表)分成指定大小的子列表(块)。
Args:
arr (list): 待分块的列表。
chunk_size (int): 每个块的大小。
Returns:
list: 包含所有子列表(块)的列表。
"""
result = []
for i in range(0, len(arr), chunk_size):
result.append(arr[i:i+chunk_size])
return result
def parse_speed_info(line_string):
"""
从包含速度信息的字符串中提取速度数值和单位。
Args:
line_string (str): 形如 "Download: 123.45 Mbit/s" 或 "Upload: 67.89 Kbit/s" 的字符串。
Returns:
tuple: 一个元组,第一个元素是浮点型的速度值,第二个元素是字符串形式的单位。
"""
# 通过空格分割字符串,并从第二个元素开始(跳过 "Download:" 或 "Upload:")
speed_info_list = line_string.split()[1::]
return (
float(speed_info_list[0]), # 将速度字符串转换为浮点数
speed_info_list[1].strip() # 获取单位字符串并去除可能的空白字符
)
def stringify_speed_info(speed, unit):
"""
根据速度值和单位生成格式化的输出字符串。
Args:
speed (float): 速度数值。
unit (str): 速度单位(例如 "Mbit/s", "Kbit/s")。
Returns:
str: 格式化后的速度描述字符串。
"""
if speed == 0:
return "zero"
# 根据原问题描述,小于600的条件主要针对Mbit/s,这里假设该条件只适用于Mbit/s
elif unit == "Mbit/s" and speed < 600.0:
return f"less than 600 {unit}"
else:
return f"{speed} {unit}"
if __name__ == "__main__":
main()
通过上述方法,我们可以高效地自动化处理大量具有相似结构的文件,从中提取和分析所需的数据,极大地提高了工作效率。
以上就是使用Python递归解析日志文件中的特定性能数据的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号