Python正则表达式可处理不同类型的日期 [英] Python regex to handle different types of dates

查看:217
本文介绍了Python正则表达式可处理不同类型的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写一个正则表达式来标识一些日期。

I am trying to write a regex to identify some dates.

我正在处理的字符串是:

the string I am working on is :

string:
'these are just rubbish 11-2-2222, 24-3-1695-194475 12-13-1111, 32/11/2000\
 these are dates 4-02-2011, 12/12/1990, 31-11-1690,  11 July 1990, 7 Oct 2012\
 these are actual deal- by 12 December six people died and in June 2000 he told, by 5 July 2001, he will leave.'

正则表达式如下:

re.findall('(\
[\b, ]\
([1-9]|0[1-9]|[12][0-9]|3[01])\
[-/.\s+]\
(1[1-2]|0[1-9]|[1-9]|Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sept|September|Oct|October|Nov|November|Dec|December)\
(?:[-/.\s+](1[0-9]\d\d|20[0-2][0-5]))?\
[^\da-zA-Z])',String)

我得到的输出是:

[(' 11-2-', '11', '2', ''),
 (' 24-3-1695-', '24', '3', '1695'),
 (' 4-02-2011,', '4', '02', '2011'),
 (' 12/12/1990,', '12', '12', '1990'),
 (' 31-11-1690,', '31', '11', '1690'),
 (' 11 July 1990,', '11', 'July', '1990'),
 (' 7 Oct 2012 ', '7', 'Oct', '2012'),
 (' 12 December ', '12', 'December', ''),
 (' 5 July 2001,', '5', 'July', '2001')]

问题:


  1. 前两个输出是错误的,因为可选表达式((?? [-/ .\s +](1 [0-9] \d\d | 20 [0-2] [0-5]))?)
    处理类似 12月12日 。我如何摆脱它们?

  1. The first two output are wrong, they come because of the optional expression ((?:[-/.\s+](1[0-9]\d\d|20[0-2][0-5]))?) put to handle cases like "12 December". How do I get rid of them?

有一种情况 2000年6月 不是

我可以用表达式实现一些可以处理这种情况而又不影响其他人的东西吗?

There is a case "June 2000" that is not handles by the expression.
Can I implement something with the expression that could handle this case without affecting others?


推荐答案

我会避免尝试获取正则表达式来解析您的日期。正如您所发现的,它可以正常运行,但很快就很难捕获边缘情况,例如无效日期,例如31/09/2018

I would avoid trying to get a regular expression to parse your dates. As you have found, it starts ok but soon becomes harder to catch edge cases, for example invalid dates, e.g. 31/09/2018

一种更安全的方法是让Python的 datetime 决定日期是否有效。然后,您可以轻松指定有效的日期范围和允许的日期格式。

A safer approach is to let Python's datetime decide if a date is valid or not. You can then easily specify valid date ranges and allowed date formats.

此脚本通过使用正则表达式提取所有单词和数字组而起作用。然后,它一次包含三个部分,并应用允许的日期格式。如果 datetime 成功解析给定格式,则将对其进行测试以确保它在允许的日期范围内。如果有效,则跳过匹配的部分,以避免在部分日期进行第二次匹配。

This script works by using the regular expression to extract all words and number groups. It then takes three parts at a time and applies the allowed date formats. If datetime succeeds in parsing a given format, it is tested to ensure it falls within your allowed date ranges. If valid, the matching parts are skipped over to avoid a second match on a partial date.

如果找到的日期不包含年份,则 default_year :

If the date found does not contain a year, a default_year is assumed:

from itertools import tee
from datetime import datetime
import re


valid_from = datetime(1920, 1, 1)
valid_to = datetime(2030, 1, 1)
default_year = 2018

dt_formats = [
    ['%d', '%m', '%Y'], 
    ['%d', '%b', '%Y'],
    ['%d', '%B', '%Y'],
    ['%d', '%b'],
    ['%d', '%B'],
    ['%b', '%d'],
    ['%B', '%d'],
    ['%b', '%Y'],
    ['%B', '%Y'],
]

text = """these are just rubbish 11-2-2222, 24-3-1695-194475 12-13-1111, 32/11/2000
these are dates 4-02-2011, 12/12/1990, 31-11-1690,  11 July 1990, 7 Oct 2012
these are actual deal- by 12 December six people died and in June 2000 he told, by 5 July 2001, he will leave."""

t1, t2, t3 = tee(re.findall(r'\b\w+\b', text), 3)
next(t2, None)
next(t3, None)
next(t3, None)
triples = zip(t1, t2, t3)

for triple in triples:
    for dt_format in dt_formats:
        try:
            dt = datetime.strptime(' '.join(triple[:len(dt_format)]), ' '.join(dt_format))

            if '%Y' not in dt_format:
                dt = dt.replace(year=default_year)

            if valid_from <= dt <= valid_to:
                print(dt.strftime('%d-%m-%Y'))

                for skip in range(1, len(dt_format)):
                    next(triples)
            break

        except ValueError:
            pass

对于您输入的文本,将显示:

For the text you have given, this would display:

04-02-2011
12-12-1990
11-07-1990
07-10-2012
12-12-2018
01-06-2000
05-07-2001

这篇关于Python正则表达式可处理不同类型的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆