如何在Python中使用NLP,RegEx查找句子中的日期

2024-09-28 19:01:34 发布

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

有谁能给我一些在python中查找和解析日期(任何格式,“Aug06”,“Aug2006”,“2008年8月2日”,“2006年8月19日”,“08-06”,“01-08-06”)的方法吗。在

我遇到了这个问题,但它是在perl中。。。 Extract inconsistently formatted date from string (date parsing, NLP)

任何建议都会有帮助。在


Tags: 方法fromdatestringnlp格式extract建议
2条回答

这将查找示例语句中的所有日期:

for match in re.finditer(
    r"""(?ix)             # case-insensitive, verbose regex
    \b                    # match a word boundary
    (?:                   # match the following three times:
     (?:                  # either
      \d+                 # a number,
      (?:\.|st|nd|rd|th)* # followed by a dot, st, nd, rd, or th (optional)
      |                   # or a month name
      (?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*)
     )
     [\s./-]*             # followed by a date separator or whitespace (optional)
    ){3}                  # do this three times
    \b                    # and end at a word boundary.""", 
    subject):
    # match start: match.start()
    # match end (exclusive): match.end()
    # matched text: match.group()

它绝对不是完美的,并且容易错过一些日期(特别是如果它们不是英语的-21. Mai 2006将失败,以及4ème décembre 1999),并且匹配像August Augst Aug这样的无意义内容,但是由于在示例中几乎所有内容都是可选的,所以在regex级别上没有什么可以做的。在

下一步是将所有匹配项输入到解析器中,看它是否能够将它们解析为一个合理的日期。在

正则表达式无法正确解释上下文。想象一个(愚蠢的)文本,比如You'll find it in box 21. August 3rd will be the shipping date.,它将匹配21. August 3rd,当然这是无法解析的。在

from dateutil import parser


texts = ["Aug06", "Aug2006", "August 2 2008", "19th August 2006", "08-06", "01-08-06"]
for text in texts:
    print text, parser.parse(text)


Aug06            2010-08-06 00:00:00
Aug2006          2006-08-28 00:00:00
August 2 2008    2008-08-02 00:00:00
19th August 2006 2006-08-19 00:00:00
08-06            2010-08-06 00:00:00
01-08-06         2006-01-08 00:00:00

如果您想在较长的文本中找到这些日期,那么尝试搜索数字和月份组,并将它们提供给这个解析器。如果文本看起来不像日期,则会引发异常。在

^{pr2}$

相关问题 更多 >