【问题标题】:Issue lies with variable definition. I am unsure how to resolve问题在于变量定义。我不确定如何解决
【发布时间】:2019-08-19 22:05:39
【问题描述】:

我正在尝试使用正则表达式从文本文件中提取日期。 文本文件中的日期线示例:

1530Z   1 FEB 1990   

使用的正则表达式:

date_matcher = re.compile("^([0-9]{4}[z].[0-9]+.[A-Z]{3}.[0-9]{4})")

我尝试修改我正在使用的代码,然后从正则表达式中“提取”日期和时间。这是代码:

# get just the data lines, without headers.
def get_data_lines( path ):

     # where we are putting data lines (no header lines)
     data_lines = []

     #for root, dirs,  files in os.walk(path):
         #print oot, dirs, dirs2, files
     if os.path.isfile(str(path)) and (str(path.endswith('.dat'))):
         with open(path) as f:
             dt = None
             for line in f:

                 # check that line isn't empty
                 if line.strip():

                     # the compiled matcher will return a match object
                     # or null if no match was found.
                     result = data_matcher.match(line)
                     if result:
                         data_lines.append((line,dt))
                     else:
                         dtres = date_matcher.match(line)
                         if dtres:
                             line = [ w for w in line.split() if w]
                             date = line[-4:]
                             if len(date) == 4:
                                 time, day, month, year = date
                                # print date
                                 # fix the date bits
                                 time  = time.replace('Z','')
                                 day   = int(day)
                                 month = strptime(month,'%b').tm_mon
                                 year  = int(year)

                                 hour, minutes = re.findall('..',time)
                                 dt = datetime(year,month,day,int(hour),int(minutes))

     return data_lines

dt = datetime(year,month,day,int(hour),int(minutes)) 都是一行,但在我格式化它时看起来不是这样,所以我认为这会有助于指出出去。

我知道问题在于 dt = None。当我让它打印出我要提取的文件目录中的所有日期时,它只会为我有日期的文件打印 NONE 。

预期结果是 dt 变量被创建为空,并在遇到日期时被替换为日期。 所以对于这个例子,我想要的是:1530 1 2 1990
对于线路:1530Z 1 FEB 1990 并且能够从我分配给它的给定对象中调用月、日、年、时间。

【问题讨论】:

    标签: python regex python-3.6


    【解决方案1】:

    这是我更改正则表达式模式的解决方案。我用date_matcher = re.compile(r"((\d{4})[Z]).*(\d{1,2}).(\w{3}).(\d{4})") 替换了它,它应该会给你你正在寻找的结果。

    从这里开始,我使用re.sub 简单地使日期看起来像您想要的那样(即比原始日期更具可读性)。它删除 Z 字符,将月份名称更改为相应的月份编号,并删除字符串中间的多余空格。

    import re
    from time import strptime
    from datetime import datetime
    
    data_matcher = re.compile('^(\s\s[0-2])')
    date_matcher = re.compile(r"((\d{4})[Z]).*(\d{1,2}).(\w{3}).(\d{4})")
    
    def get_data_lines( path ):
    
        # where we are putting data lines (no header lines)
        data_lines = []
    
        #for root, dirs,  files in os.walk(path):
        #print oot, dirs, dirs2, files
        if os.path.isfile(str(path)) and (str(path.endswith('.dat'))):
             with open(path) as f:
                dt = None
                for line in f:
    
                # check that line isn't empty
                if line.strip():
    
                 # the compiled matcher will return a match object
                 # or null if no match was found.
                    result = data_matcher.match(line)
    
                    if result:
                        dt = re.sub(r'((\d{4})[Z])', r'\2', line) #Remove Z character
                        month = date_matcher.match(line).group(4)
                        dt = re.sub(r'\b(\w{3})\b', str(strptime(month,'%b').tm_mon), line) #Change month name to number
                        dt = re.sub(r'\s+', ' ', dt) #Remove extra whitespace
                        data_lines.append((line,dt))
                        print('Data Lines: ', data_lines)
    
                    else:
                        line = [ w for w in line.split() if w]
                        date = line[-4:]
    
                        if len(date) == 4:
                            time, day, month, year = date
                            # print date
                            # fix the date bits
                            time  = time.replace('Z','')
                            day   = int(day)
                            month = strptime(month,'%b').tm_mon                         
                            year  = int(year)   
                            hour, minutes = re.findall('..',time)
                            dt = datetime(year,month,day,int(hour),int(minutes)) 
                            data_lines.append((line,dt))
    
        return data_lines
    

    【讨论】:

    • 所以函数 'def get_data_lines( path ):' 也抓取数据线。我有两个不同的正则表达式匹配器。这个:data_matcher = re.compile('^(\s\s[0-2])') 用于数据。
    • 知道了。我将调整我的代码以反映这一点。如果我的回答对您有用,请将其标记为已接受。
    • 我明确将其标记为已接受。修复该正则表达式使其立即打印出正确的日期。我也忘记了 python 从 0 开始,用于定义我要提取的其他变量,而不是 1 用于“行中的列” EX:height = row[0:5] 而不是 row[1:6] 看起来它开始了拉出正确的线,但会切断一些数据。
    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多