代码之家  ›  专栏  ›  技术社区  ›  user9431057

使用RE-Python使用文本提取不同的日期结构

  •  1
  • user9431057  · 技术社区  · 8 年前

    我有不同格式的日期字符串。例如

    sample_str_1 = 'this amendment of lease, made and entered as of the  10th day of august, 2016,   by and between john doe and jane smith'
    

    还有另一个字符串,其中的日期为,

    sample_str_2 ='this agreement, made and entered as of May 1, 2016, between john doe and jane smith'
    

    为了从第一个字符串中提取日期,我做了如下操作,

    match = re.findall(r'\S+d{4}\s+', sample_str_1)
    

    这将给出一个空列表。

    对于第二个字符串,我使用了与第一个字符串相同的方法,得到了一个空字符串。

    我也试过了 datefinder 它给了我这样的输出,

    import datefinder
    match = datefinder.find_dates(sample_str_1)
    
    for m in match:
        print(m)
    
    >> 2016-08-01 00:00:00
    

    上述输出错误,应 2016-08-10 00:00:00

    我试着用另一种方法 post

    match = re.findall(r'\d{2}(?:january|february|march|april|may|june|july|august|september|october|november|december)\d{4}',sample_str_1)
    

    这又给了我一张空名单。

    如何从字符串中提取这样的日期?是否有一种通用方法来提取具有文本和数字的日期?任何帮助都将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Srdjan M.    8 年前

    正则表达式 : (?:(\d{1,2})(?:th|nd|rd).* ([a-z]{3})[a-z]*|([a-z]{3})[a-z]* (\d{1,2})),\s*(\d{4})

    Python代码 :

    regex = re.compile('(?:(\d{1,2})(?:th|nd|rd).* ([a-z]{3})[a-z]*|([a-z]{3})[a-z]* (\d{1,2})),\s*(\d{4})', re.I)
    
    for x in regex.findall(text):
        if x[0] == '':
            date = '-'.join(filter(None, x))
        else:
            date = '%s-%s-%s' % (x[1],x[0],x[4])
    
        print(datetime.datetime.strptime(date, '%b-%d-%Y').date())
    

    输出:

    2016-08-10
    2016-05-01
    

    Code demo