提取以 'st'、'nd'、'rd'、'th' 结尾的日期,同时使用 RegEx 将日期与月份交换

Extractall for the dates ending with 'st','nd', 'rd','th' while swapping days with months using RegEx

我在 pandas 数据框列的文本中得到了这些日期。

import pandas as pd
sr = pd.Series(['text Mar 20, 2009 text', 'text March 20, 2009 text', 'text 20 Mar. 2009 text', 'text Sep 2010 text','text Mar 20th, 2009 text ','text Mar 21st, 2009 text'])

当我使用正则表达式时,我明白了。

a=sr.str.extractall(r'((?P<day>(?:\d{2} )?(?P<month>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*)) (?:\d{2}[-/th|st|nd|rd\s]*[,.]* )?(?P<year>\d{4}))')


       all              day     month  year
match               
0   0   Mar 20, 2009    Mar      Mar    2009
1   0   March 20, 2009  March    March  2009
2   0   20 Mar. 2009    20 Mar.  Mar.   2009
3   0   Sep 2010        Sep      Sep    2010
4   0   Mar 20th, 2009  Mar      Mar    2009
5   0   Mar 21st, 2009  Mar      Mar    2009

如何将日期(20 日、20 日、21 日...)放入日列?

一个解决方案pandas(为什么要重新发明轮子?):

    import pandas as pd
    df = sr.to_frame(name='all')
    df['all'] = pd.to_datetime(df['all'])
    df['day'] = df['all'].dt.day
    df['month'] = df['all'].dt.strftime('%b')
    df['year'] = df['all'].dt.year

输出:

         all  day month  year
0 2009-03-20   20   Mar  2009
1 2009-03-20   20   Mar  2009
2 2009-03-20   20   Mar  2009
3 2010-09-01    1   Sep  2010
4 2009-03-20   20   Mar  2009
5 2009-03-21   21   Mar  2009

也许另一种解决方案是使用 PyPi regex module 和分支重置组 (?| 来匹配日期和月份。

没有命名组的模式:

\b((?|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*(?: (\d{2}(?:th|st|nd|rd)?)?[,.])?|(\d{2}) (?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*)?) (\d{4}))

Regex demo

import pandas as pd
import regex

pattern = r"\b(?P<all>(?|(?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*(?: (?P<day>\d{2}(?:th|st|nd|rd)?)?[,.])?|(?P<day>\d{2}) (?:(?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*)?) (?P<year>\d{4}))"

items = [
    'text Mar 20, 2009 text',
    'text March 20, 2009 text',
    'text 20 Mar. 2009 text',
    'text Sep 2010 text',
    'text Mar 20th, 2009 text ',
    'text Mar 21st, 2009 text'
]
res = map(lambda x: regex.findall(pattern, x)[0], items)
df = pd.DataFrame(res)
df.columns = ['all', 'month', 'day', 'year']
print(df)

输出

              all month   day  year
0    Mar 20, 2009   Mar    20  2009
1  March 20, 2009   Mar    20  2009
2    20 Mar. 2009   Mar    20  2009
3        Sep 2010   Sep        2010
4  Mar 20th, 2009   Mar  20th  2009
5  Mar 21st, 2009   Mar  21st  2009