从文本Python中识别和提取日期的最佳方法?

2024-03-28 15:08:28 发布

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

作为我正在进行的一个更大的个人项目的一部分,我试图从各种文本源中分离出内联日期。

例如,我有一大串字符串(通常采用英语句子或语句的形式),它们有多种形式:

Central design committee session Tuesday 10/22 6:30 pm

Th 9/19 LAB: Serial encoding (Section 2.2)

There will be another one on December 15th for those who are unable to make it today.

Workbook 3 (Minimum Wage): due Wednesday 9/18 11:59pm

He will be flying in Sept. 15th.

虽然这些日期与自然文本一致,但没有一个日期本身是以特定的自然语言形式出现的(例如,没有“会议将在明天两周后举行”——这都是明确的)。

作为一个对这种处理没有太多经验的人,什么是最好的开始?我研究过诸如dateutil.parser模块和parsedatetime之类的东西,但这些似乎是在您隔离了日期之后用于的。

因此,有没有什么好的方法来提取日期和无关的文本

input:  Th 9/19 LAB: Serial encoding (Section 2.2)
output: ['Th 9/19', 'LAB: Serial encoding (Section 2.2)']

或者类似的?这类处理似乎是由Gmail和Apple Mail等应用程序完成的,但是否可以用Python实现呢?


Tags: 项目字符串文本labserialsection语句be
3条回答

如果您能够识别实际包含日期信息的段,那么使用parsedatetime可以非常简单地解析它们。有几件事要考虑,即你的日期没有年,你应该选择一个地点。

>>> import parsedatetime
>>> p = parsedatetime.Calendar()
>>> p.parse("December 15th")
((2013, 12, 15, 0, 13, 30, 4, 319, 0), 1)
>>> p.parse("9/18 11:59 pm")
((2014, 9, 18, 23, 59, 0, 4, 319, 0), 3)
>>> # It chooses 2014 since that's the *next* occurence of 9/18

当你有无关的文本时,它并不总是完美地工作。

>>> p.parse("9/19 LAB: Serial encoding")
((2014, 9, 19, 0, 15, 30, 4, 319, 0), 1)
>>> p.parse("9/19 LAB: Serial encoding (Section 2.2)")
((2014, 2, 2, 0, 15, 32, 4, 319, 0), 1)

老实说,这似乎是一个很简单的问题,可以为特定格式进行解析,并从每个句子中选出最有可能的一个。除此之外,这将是一个不错的机器学习问题。

我也在寻找解决办法,但找不到,所以我和一个朋友建立了一个工具来解决这个问题。我想如果其他人觉得有用的话,我会回来分享的。

datefinder -- find and extract dates inside text

import datefinder
string_with_dates = """
                    entries are due by January 4th, 2017 at 8:00pm
                    created 01/15/2005 by ACME Inc. and associates.
                    """
matches = datefinder.find_dates(string_with_dates)
for match in matches:
    print match

相关问题 更多 >