作为我正在进行的一个更大的个人项目的一部分,我试图将内联日期从各种文本源中分离出来。
例如,我有一大串字符串(通常以英语句子或语句的形式),这些字符串的形式多种多样:
中央设计委员会会议星期二晚上十时二十二日下午六时三十分 第9/19号实验室:串行编码(2.2节) 将在12月15日为那些今天无法到达的人举行另一次会议。 工作簿3(最低工资):截止日期:星期三上午11:59分 他将于9月1日乘飞机。第十五。
虽然这些日期与自然文本是一致的,但它们中没有一种是以特定的自然语言形式出现的(例如,没有“明天起两周的会议”-都是明确的)。
作为一个对这类处理没有太多经验的人,什么是最好的开始呢?我已经研究过像dateutil.parser模块和分段时间这样的东西,但它们似乎是在您隔离日期之后使用的。
正因为如此,有什么好方法来提取日期和无关的文本吗?
input: Th 9/19 LAB: Serial encoding (Section 2.2)
output: ['Th 9/19', 'LAB: Serial encoding (Section 2.2)']或者类似的东西?这类处理似乎是由Gmail和Apple之类的应用程序完成的,但用Python实现是否可行呢?
发布于 2016-01-28 18:20:06
我也在寻找解决这个问题的方法,却找不到任何解决办法,所以我和一个朋友建立了一个工具来解决这个问题。我想我会回来和别人分享,以防别人发现这很有帮助。
下面是一个例子:
import datefinder
string_with_dates = '''
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.
We expect to deliver this between late 2021 and early 2022.
'''
matches = datefinder.find_dates(string_with_dates)
for match in matches:
print(match)发布于 2018-10-03 22:21:09
from sutime import SUTime
import os
import json
from dateparser.search import search_dates
str1 = "Let's meet sometime next Thursday"
# You'll get more information about these jar files from SUTime's github page
jar_files = os.path.join(os.path.dirname(__file__), 'jars')
sutime = SUTime(jars=jar_files, mark_time_ranges=True)
print(json.dumps(sutime.parse(str1), sort_keys=True, indent=4))
"""output:
[
{
"end": 33,
"start": 20,
"text": "next Thursday",
"type": "DATE",
"value": "2018-10-11"
}
]
"""
print(search_dates(str1))
#output:
#[('Thursday', datetime.datetime(2018, 9, 27, 0, 0))]虽然我尝试过其他模块,如dateutil、datefinder和natty (无法让鸭子使用python),但这两个模块似乎给出了最有希望的结果。
来自SUTime的结果更可靠,从上面的代码片段中可以清楚地看到。但是,在一些基本的场景(如解析文本)中,SUTime失败。
“我要到9/19才有空”
或
“我不能在9月18日至9月20日之间上班。”
它没有给出第一个文本的结果,只给出第二个文本的月份和年份。然而,这在search_dates方法中处理得很好。search_dates方法更具侵略性,它将给出与输入文本中的任何单词相关的所有可能日期。
我还没有找到一种严格解析search_methods中日期的文本的方法。如果我能找到一种方法,这将是我的第一选择SUTime,我也会确保更新这个答案,如果我找到它。
发布于 2018-07-13 11:25:18
您可以使用dateutil模块的parse方法和fuzzy选项。
>>> from dateutil.parser import parse
>>> parse("Central design committee session Tuesday 10/22 6:30 pm", fuzzy=True)
datetime.datetime(2018, 10, 22, 18, 30)
>>> parse("There will be another one on December 15th for those who are unable to make it today.", fuzzy=True)
datetime.datetime(2018, 12, 15, 0, 0)
>>> parse("Workbook 3 (Minimum Wage): due Wednesday 9/18 11:59pm", fuzzy=True)
datetime.datetime(2018, 3, 9, 23, 59)
>>> parse("He will be flying in Sept. 15th.", fuzzy=True)
datetime.datetime(2018, 9, 15, 0, 0)
>>> parse("Th 9/19 LAB: Serial encoding (Section 2.2)", fuzzy=True)
datetime.datetime(2002, 9, 19, 0, 0)https://stackoverflow.com/questions/19994396
复制相似问题