我有一些模糊文本,其中包含有关日期的信息。例如:“本周六音乐会”。我想通过将引用日期作为参数来提取与“本周六”相对应的日期。 例如,假设这是 2016 年 4 月 13 日发送的电子邮件的主题,我想知道该电子邮件所指的“本周六”是在 2016 年 4 月 16 日发送的。您知道有什么软件包可以做到这一点吗?
P.S.我已经使用了 dateutil.parser,但这并不将引用日期作为参数,它为我提供了从我运行代码之日起的下一个星期六的日期。
最佳答案
dateutil.parser.parse
接受一个 default
参数,您可以使用该参数指定引用日期:
import datetime as DT
import dateutil.parser as DP
today = DT.datetime(2016, 4, 13)
for text in ('today', 'tomorrow', 'this Sunday', 'Wednesday next week',
'next week Wednesday',
'next thursday', 'next tuesday in June', '11/28',
'Concert this Saturday'
"lunch with Andrew @ Mon Mar 7, 2016",
'meeting on Tuesday, 3/29'):
dp_date = DP.parse(text, default=today, fuzzy=True)
print('{:35} --> {}'.format(text, dp_date))
产量
today --> 2016-04-13 00:00:00
tomorrow --> 2016-04-13 00:00:00 should be 2016-04-14
this Sunday --> 2016-04-17 00:00:00
Wednesday next week --> 2016-04-13 00:00:00
next week Wednesday --> 2016-04-13 00:00:00
next thursday --> 2016-04-14 00:00:00
next tuesday in June --> 2016-06-14 00:00:00 should be 2016-06-07
11/28 --> 2016-11-28 00:00:00
Concert this Saturday --> 2016-04-16 00:00:00
lunch with Andrew @ Mon Mar 7, 2016 --> 2016-03-07 00:00:00
meeting on Tuesday, 3/29 --> 2016-03-29 00:00:00
但请注意,并非所有短语都能正确解析。
关于python - 通过给出不是当前日期的引用日期作为参数来从文本中提取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37311984/