gpt4 book ai didi

Python 帮助 - 解析数据包日志

转载 作者:行者123 更新时间:2023-11-28 18:56:05 26 4
gpt4 key购买 nike

我正在编写一个简单的程序,它将把来自 wireshark 的数据包转储的日志文件解析为更易读的形式。我正在用 python 做这件事。

目前我卡在这部分了:

for i in range(len(linelist)):
if '### SERVER' in linelist[i]:
#do server parsing stuff

packet = linelist[i:find("\n\n", i, len(linelist))]

linelist 是使用 readlines() 方法创建的列表,因此文件中的每一行都是列表中的一个元素。我正在遍历所有出现的“### SERVER”,然后抓取它之后的所有行,直到下一个空行(表示数据包结束)。我一定是做错了什么,因为不仅 find() 不起作用,而且我觉得有更好的方法来获取 ### SERVER 和下一个空白行之间的所有内容。

有什么想法吗?

最佳答案

查看 file.readlines()文档:

file.readlines([sizehint])

Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.

file.readline()文档:

file.readline([size])

Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.

尾随换行符保留在字符串中 - 意味着 linelist 中的每一行最多包含 一个 换行符。这就是为什么您在任何行中都找不到 "\n\n" 子字符串的原因 - 查找整个空行(或 EOF 处的空行):

if myline in ("\n", ""):
handle_empty_line()

注意:我试图解释 find 行为,但是 pythonic 解决方案看起来与您的代码片段非常不同。

关于Python 帮助 - 解析数据包日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/293444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com