从文本文件中检索随机预格式化的文本

时间:2013-04-23 14:40:15

标签: python regex gettext

我正在编写一个python脚本来获取格式为StartTime="mm/dd/yyyy hh:mm:ss:ccc"EndTime="mm/dd/yyyy hh:mm:ss:ccc"的字符串,该字符串位于文本文件中。

所以我继续搜索StartTimeEndtime,但我怎样才能获得(="mm/dd/yyyy hh:mm:ss:ccc")之后的内容?当我收到StartTimeEndTime字符串时,我想将它们保存在另一个带有函数saveIntoFile(File, textToSave)的文本文件中,但我想我自己可以处理这部分内容。

def getTimeCode(File) :
    fopen = open(File, 'r')    
    text = fopen.read()
    for t in text :
        if t == "StartTime" :
            #what should I do now ?
        if t == "EndTime" :
            #what should I do now ?

def saveIntoFile(filename, textToSave):

1 个答案:

答案 0 :(得分:1)

import re

def getTimeCode(fn):
    with open(fn, 'r') as f:
        for line in f:
            m = re.search(r'(\w)="(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d:\d\d\d)"', line)
            if m:
                if m.group(1) == 'StartTime':
                    # do something with m.group(2)
                elif m.group(1) == 'EndTime':
                    # do something with m.group(2)
                else:
                    # m.group(1) unknown