如何比较单个文本文件中的行(具有时间戳)?

时间:2019-02-09 15:15:51

标签: python file text

我的文本文件带有以下几行:

[Thu Jan  3 09:28:11 2019]:(sending publish)
[Thu Jan  3 09:28:14 2019]:(sending publish)
[Thu Jan  3 09:28:17 2019]:(not connect )
[Thu Jan  3 09:28:19 2019]:(sending publish)
[Thu Jan  3 09:28:21 2019]:(sending publish)

现在,我想检查文本文件中的时间戳,是否还有"sending publish"项,行之间的时差也为3秒。

如果发送发布不可用,则需要在其中打印文本(不连接)

从第4行开始,需要检查相差3秒的行。

我也找不到任何线索,也没有任何Python代码可以比较单个文件中的行(具有时间戳)。

请提供任何示例/代码的支持。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的要求,则需要构建的脚本应完成2个任务:

  1. 使用python从txt文件读取文本
  2. 从行字符串中解析所需的信息

从文件读取

以下是在python中打开和读取txt文件的示例代码:

f = open("demofile.txt", "r")
for row in f:
  print(row)

更多信息-https://www.w3schools.com/python/python_file_open.asp

字符串解析

为此,您可以同时使用字符串切片或正则表达式搜索,以下是这两者的一些信息:

  1. 正则表达式-https://docs.python.org/3/howto/regex.html
  2. 字符串切片-https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types

编辑

您可以在python中使用datetime包来计算两个日期传递的时间-https://docs.python.org/3/library/datetime.html

希望有帮助!