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

Sof*_*tic 4 python regex parsing nlp

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

我遇到了这个问题,但它是在 perl 中... 从字符串中提取格式不一致的日期(日期解析,NLP)

任何建议都会有所帮助。

Tim*_*ker 5

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

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()
Run Code Online (Sandbox Code Playgroud)

这绝对不是完美的,并且容易错过一些日期(特别是如果它们不是英文的 -21. Mai 2006会失败,以及4ème décembre 1999),并且匹配像 一样的废话August Augst Aug,但是由于在您的示例中几乎所有内容都是可选的,因此您无能为力在正则表达式级别。

下一步是将所有匹配项输入解析器,看看它是否可以将它们解析为合理的日期。

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