【问题标题】:Extract Different Date Structures with Text Using RE- Python使用 RE-Python 提取带有文本的不同日期结构
【发布时间】:2018-08-10 01:01:36
【问题描述】:

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

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)

这又给了我一个空列表。

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

【问题讨论】:

  • 也许你应该看看dateparser 包。在这里重新发明轮子没有多大意义……
  • @ctwheels 这没什么,我用date_parse = DateDataParser().get_date_data(sample_str_1) 得到{'date_obj': None, 'locale': None, 'period': 'day'}
  • 只需要匹配特定短语[day]st/nd/rd/th day of [month], [year][month] [day], [year]吗?还有许多其他方法可以格式化日期。
  • 你只有10th day of august, 2016May 1, 2016两种格式的日期?
  • @CAustin 是的,这是一种格式,而字符串 2 具有不同的格式。

标签: regex string date python-3.5


【解决方案1】:

正则表达式(?:(\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

【讨论】:

  • 这很好用。如果我有2nd3rd 等我该怎么办。我尝试添加(?:(\d{1,2})th|nd|rd.* (.. 它打印为空白。我该如何添加? (因为我是新用户,所以我还不能投票,因为你应该得到一个)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
相关资源
最近更新 更多