python通过将引用日期(不是当前的d)作为参数,从文本中提取日期

2024-03-29 12:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些包含日期信息的模糊文本。例如:“本周六音乐会”。我想通过将引用日期作为参数来提取与“this Saturday”对应的日期。 例如,假设这是2016-04-13发送的电子邮件的主题,我想得到这封电子邮件所指的“本周六”是2016-04-16。你知道有什么包裹能做到这一点吗?你知道吗

另外,我用过dateutil.parser文件但这并没有将引用日期作为参数,而是将从运行代码的日期算起的下一个星期六作为日期。你知道吗


Tags: 文件代码文本信息parser主题参数电子邮件
1条回答
网友
1楼 · 发布于 2024-03-29 12:02:02

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

但是,请注意,并非所有短语都能正确解析。你知道吗

相关问题 更多 >