首页 > 解决方案 > 如何从 .t​​xt 文件中提取数据(时间)?

问题描述

我有 .txt 文件,从 txt 文件我想要所有的时间来检查性能。如何让所有时间都进入新列表?

下面是我的 .txt 文件:

03-21 12:09:34.123 application open
03-21 12:09:35.122 date 
03-21 12:09:36.124 completed
03-21 12:09:37.125 None

以下是我尝试过的:

def memory(self):
    self.empty = []
    time_x = []
    heap_y = [0,20,40,60,80,100,120]
    pattren =re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$')
    with open("C:\\Sakurai_Robot\\testlogs\\logcat_105010176.log", "r") as gummi:
        for i in gummi.readlines():
            if pattren.search(i) !=None:
                self.empty.append(i.rstrip('\n'))

        print self.empty

我只想要这样的时间:

12:09:34
12:09:35
12:09:36
12:09:37

但我无法获得。有什么方法可以让我们一直进入新列表?

标签: python-2.7

解决方案


这里的代码应该可以解决您的问题。

    import re
    output = []
    p = re.compile('\d\d:\d\d:\d\d')
    with open("path", "r") as fle:
        for i in fle.readlines():
            lst = p.findall(p)
            for match in lst:
                output.append(match)

    for a in output:
        print(a)

当针对您的输入运行时,输出如下:

    12:09:34
    12:09:35
    12:09:36
    12:09:37

推荐阅读