首页 > 解决方案 > 从字符串中识别和提取日期 - Python

问题描述

我正在寻找从许多不同的字符串中识别和提取日期。日期的格式可能不同。我一直在使用 datefinder 包,但在保存输出时遇到了一些问题。

目标:从字符串中提取日期,该日期可能以多种不同方式格式化(即 April,22 或 4/22 或 22-Apr 等),如果没有日期,则将值设置为“None”并附加带有日期或“无”的日期列表。

请参阅下面的示例。

示例 1:(这会返回一个日期,但不会附加到我的列表中)


import datefinder

extracted_dates = []
sample_text = 'As of February 27, 2019 there were 28 dogs at the kennel.'

matches = datefinder.find_dates(sample_text)
for match in matches:
    if match == None:
        date = 'None'
        extracted_dates.append(date)
    else:
        date = str(match)
        extracted_dates.append(date)

示例 2:(这不会返回日期,也不会附加到我的列表中)

import datefinder

extracted_dates = []
sample_text = 'As of the date, there were 28 dogs at the kennel.'

matches = datefinder.find_dates(sample_text)
for match in matches:
    if match == None:
        date = 'None'
        extracted_dates.append(date)
    else:
        date = str(match)
        extracted_dates.append(date)

标签: pythondatenlpdatefinder

解决方案


我试过使用你的包,但似乎没有快速和通用的方法来提取你的例子中的真实日期。

我改为使用DateParser包,更具体地说是search_dates方法

我仅在您的示例中对其进行了简要测试。

from dateparser.search import search_dates

sample_text = 'As of February 27, 2019 there were 28 dogs at the kennel.'
extracted_dates = []

# Returns a list of tuples of (substring containing the date, datetime.datetime object)
dates = search_dates(sample_text)

if dates is not None:
  for d in dates:
    extracted_dates.append(str(d[1]))
else:
  extracted_dates.append('None')

print(extracted_dates)

推荐阅读