如何从.txt文件中提取数据(时间)?

时间:2019-07-08 11:59:23

标签: python-2.7

我有.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

但是我无法获得。有什么办法可以使所有时间都进入新列表吗?

2 个答案:

答案 0 :(得分:0)

此代码可解决您的问题。

    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

答案 1 :(得分:0)

您也可以完全不用正则表达式来完成它:

timestamps = []
with open("C:\\Sakurai_Robot\\testlogs\\logcat_105010176.log", "r") as gummi:
    for i in gummi.readlines():
        timestamps.append(i.split(" ")[1].split(".")[0])

print timestamps