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

Python如何从无固定格式字符串中提取指定格式的月份时间区间

Python实现月份区间提取标准化方案

实现思路

  • 预定义月份名称到3字母标准缩写的映射,兼容全拼和前3字母缩写输入
  • 用正则表达式从无格式文本中匹配完整的月份区间片段
  • 对匹配到的起止月份、年份做格式化处理,输出统一格式

完整代码实现

import re

def standardize_month_range(text: str) -> str | None:
    # 月份映射:全拼/小写缩写对应标准3字母大写缩写
    month_map = {
        'jan': 'Jan', 'january': 'Jan',
        'feb': 'Feb', 'february': 'Feb',
        'mar': 'Mar', 'march': 'Mar',
        'apr': 'Apr', 'april': 'Apr',
        'may': 'May',
        'jun': 'Jun', 'june': 'Jun',
        'jul': 'Jul', 'july': 'Jul',
        'aug': 'Aug', 'august': 'Aug',
        'sep': 'Sep', 'september': 'Sep',
        'oct': 'Oct', 'october': 'Oct',
        'nov': 'Nov', 'november': 'Nov',
        'dec': 'Dec', 'december': 'Dec'
    }
    # 匹配月份区间的正则,忽略大小写
    pattern = re.compile(
        r'([a-zA-Z]{3,9})[\s-](\d{2,4})\s*(?:to|-)\s*([a-zA-Z]{3,9})[\s-](\d{2,4})',
        re.IGNORECASE
    )
    match = pattern.search(text)
    if not match:
        return None
    # 提取匹配到的四个分组:起始月份、起始年份、结束月份、结束年份
    start_month_raw, start_year_raw, end_month_raw, end_year_raw = match.groups()
    # 标准化月份
    try:
        start_month = month_map[start_month_raw.lower()]
        end_month = month_map[end_month_raw.lower()]
    except KeyError:
        return None
    # 标准化年份,取后两位
    start_year = start_year_raw[-2:]
    end_year = end_year_raw[-2:]
    # 拼接输出格式
    return f"{start_month}-{start_year} to {end_month}-{end_year}"

测试用例

# 测试示例1
text1 = 'some text here Jul-21 to September-2021 some more text'
print(standardize_month_range(text1))  # 输出:Jul-21 to Sep-21

# 测试示例2
text2 = 'some text july 2021 - sep21 some more text'
print(standardize_month_range(text2))  # 输出:Jul-21 to Sep-21

可扩展说明

  • 如果需要处理多个区间共存的场景,可以把search方法换成findall,遍历所有匹配结果即可
  • 如果需要兼容更复杂的分隔符场景,可调整正则表达式中的分隔符匹配规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:45:02