Python 从日志文件创建表



输入是一个日志文件,基本上包含实验参与者的反应时间和其他数据。我想要的输出是一个表格,其中每条信息都在自己的一个字段中,以便我可以计算列等的平均值。 我在这里和那里遇到了一些困难,希望有人可以提供帮助,因为我是 Python 的新手。到目前为止,我所拥有的是:

# loading file and reading it character by character:
with open("......log") as characters:
while True:
character = characters.read(1)
if not character:
break
print(character)
# the idea here is: if the character is a tab, go to the next column. If it is the end of a line, go to a new row. Otherwise print the character. This should fill each table field with one string/number.
for character in range(???):   #what do I enter in "range"? I want the for loop   
to run over all characters in the file 
if character == 't':
#go to next column. My idea: create an empty table first, with 
variables c = number of columns and r = number of rows, 
so at this point I can enter "c = c + 1"
elif character == 'n':
#go to next row -> r = r + 1
else
print(character)

所以总结一下,我的问题是:
1(我range输入什么?
2( 如何实现添加列和行?我可以从字面上键入c = c+1如果我之前定义了 c,它会起作用吗?
3( ...我之前如何定义c,即如何初始化空表?还是有另一种优雅的方式?

提前感谢您,如果我无法以完全有意义的方式表达某些事情,我深表歉意,我对此仍然很陌生,只有 Matlab 的经验,这是完全不同的

您应该将日志文件视为通常的分隔文件。 我建议您使用熊猫read_csv指定要在日志文件中定义数据的分隔符。

例如,以下文本是我的日志:

2019-12-11 22:56:19,467 - INFO - test
2019-12-11 22:58:10,228 - INFO - test
2019-12-11 22:58:23,968 - INFO - test
2019-12-11 22:58:34,459 - INFO - test

如果要为短划线 (-( 之间的每个值定义一列,可以使用以下代码:

import pandas as pd
data = pd.read_csv("test.log", delimiter = "-", header = None)
print(data)
print(data.head())

假设您的日志如下所示

24    378    58
6     49     1

并且您希望获得列的平均值,如

15    213.5    29.5

那么以下实现就足够了:

import functools
import re

def sum(columnTotals, line):
cells = re.split(r't+', line)
for cell in enumerate(cells):
columnTotals[cell[0]] = columnTotals.get(cell[0], 0) + float(cell[1])
return columnTotals

def main():
with open('/path/to/log') as log:
rows = [line.strip() for line in log if line.strip() != '']
columnTotals = functools.reduce(sum, enumerate(rows), {})
numberOfRows = len(rows)
means = [columnTotal/numberOfRows for columnTotal in columnTotals.values()]

if __name__ == '__main__':
main()

免责 声明:

  • 尚未考虑日志大小,并且此解决方案不节省空间
  • 假设输入的格式根据规范正确(例如,单元格由制表符分隔,单元格仅为数字(
  • 我还没有测试过脚本,但我相信它应该引导你找到你正在寻找的想法。

最新更新