如何从Python中的行中获取特定内容,然后拆分它们?

问题描述 投票:0回答:1

假设我有一个这样的日志文件;

{"log": "09-Sept-2023 rate-limit: info: client @ xyz 127.0.0.1#1075", "stream":"stderr", "time": "2023-09-09T04:18:22.676095594Z"} 

文件中有一堆像这样的行条目,对于每个行条目,我只想打印每行的时间“2023-09-09T04:18:22.676095594Z”值。然后一旦我有了这些行,我想拆分“。”所以我只得到

2023-09-09T04:18:22

并忽略所有毫秒和 Z。我尝试将此文件中的这些行视为单独的字典,并尝试访问“时间”的值,但这不起作用。因为我会尝试将其分配给变量并使用 .split('.') 方法。我也无法尝试使用索引,因为有些行的内容也较少。非常感谢这里的帮助。

python-3.x split
1个回答
0
投票

您最初的方法确实有效。这是我使用您提供的示例编写的脚本

file = {"log": "09-Sept-2023 rate-limit: info: client @ xyz 127.0.0.1#1075", "stream":"stderr", "time": "2023-09-09T04:18:22.676095594Z"} 
time_variable = file["time"] #fetching the 'time' index of dict 'file'
print(time_variable) #2023-09-09T04:18:22.676095594Z
clean_time = time_variable.split(".")[0] # splitting at the '.' and obtaining the first item
print(clean_time) #2023-09-09T04:18:22

此外,如果您有一个包含多行的文件,您仍然可以遵循相同的过程,但您必须将字符串(这是 readlines 默认读取的内容)转换为字典。您可以使用

eval()
方法来实现。 所以你最终会得到类似的东西

with open("logs.txt","r") as file:
    for log in file.readlines():
        item = eval(log)
        get_time(item)

其中

get_time()
是执行上一个代码片段中的操作的函数。

© www.soinside.com 2019 - 2024. All rights reserved.