You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从文本提取多格式日期:DataFrame日期提取正则问题求助

问题分析与解决方案

你当前代码的核心问题:

  1. str.extract使用错误:str.extract仅返回第一个匹配的分组结果,而非所有匹配项,且会将正则中的分组拆分成多列,无法得到你需要的所有日期拼接字符串。
  2. 正则模式覆盖不全:
    • 未匹配月份全称(如June、September)和大小写变体(如DEC、APRIL)
    • 未处理用to连接的日期格式(如03/2014 to 08/2015)
    • 未兼容仅含年份的格式(如(2015 – 2016))
    • 未考虑括号包裹的场景
  3. 正则结构冗余:过多的可选分组导致匹配逻辑混乱,无法精准覆盖目标日期格式。

修正后的实现代码

import pandas as pd

def extract_dates(df, column):
    # 正则模式:覆盖所有目标日期格式,忽略大小写
    pattern = r'(?i)\(?\s*(?:(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[\s,-]*\d{2,4}|\d{1,2}/\d{2,4}|\d{2,4})\s*(?:[-–]|to)\s*(?:(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[\s,-]*\d{2,4}|\d{1,2}/\d{2,4}|\d{2,4})\s*\)?'
    
    # 提取所有匹配的日期,并用逗号拼接
    df['Dates'] = df[column].str.findall(pattern).str.join(', ')
    return df

# 测试示例
sample_text = """Sales Assistant @ DFS Duration - June 2021 - 2023 Currently working in XYZ Within the role I am expected to achieve sales targets which I currently have no problems reaching. Job Role/Establishment - Plasterer @ XX Plasterer’s Duration - September 2016 - Nov 2016 Job Role/Establishment - Customer Advisor @ AA Duration - (2015 – 2016) Job Role/Establishment - Warehouse Operative @ xyz Duration - 03/2014 to 08/2015 In the xyz warehouse  Job Role/Establishment - Airport Terminal Assistant @ port Duration - 01/2012 - 06/2013 Working at the airport . Job Role/Establishment - Apprentice Floorer @ YY Floors Duration - DEC 2010 – APRIL 2012"""

df = pd.DataFrame({'id': ['01'], 'Raw_text': [sample_text]})
df = extract_dates(df, 'Raw_text')
print(df[['id', 'Raw_text', 'Dates']])

正则模式说明

  • (?i):忽略大小写,匹配DEC/dec/December等变体
  • \(?/\)?:匹配可选的前后括号
  • 核心匹配单元:
    • 月份+年份:(?:Jan(?:uary)?|...|Dec(?:ember)?)[\s,-]*\d{2,4}(支持缩写/全称)
    • 数字月份+年份:\d{1,2}/\d{2,4}
    • 纯年份:\d{2,4}
  • 连接符:\s*(?:[-–]|to)\s*(匹配-、–、to三种连接方式,忽略前后空格)

内容的提问来源于stack exchange,提问作者Roshankumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:10:12