python - 从字符串中识别和提取日期 - 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)
解决方案
我试过使用你的包,但似乎没有快速和通用的方法来提取你的例子中的真实日期。
我改为使用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)
推荐阅读
- flutter - 当我尝试从 api 获取数据时如何解决此错误
- sql - 执行过程时参数的数量或类型错误
- flutter - Dart (Flutter) 通用类型不匹配
- java - 将数据传输到 onSuccess() 方法
- javascript - 如何将我的帖子从 firestore 分页到我的 Javascript Web 应用程序。我没有使用除 Node.js 服务器之外的任何框架
- windows-subsystem-for-linux - 获取 mkdir:无法创建目录“wagmi”:权限被拒绝
- vb.net - 如何在 Windows 11 任务栏的系统托盘中显示秒数
- python - 如何使用pytest在python中断言二进制多行值
- angular - router-outlet 中的事件发射器,用于从子级到父级获取值
- c - 如何从程序中获取数据?