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

如何从任职时长文本提取数字并按规则换算为总月份数?

任职时长换算为月份的适配方案
  • 放弃原逻辑里直接提取所有数字的做法,改为分别匹配年份、月份对应的数值,避免数字顺序/数量不确定导致的计算错误
  • 用正则匹配规则覆盖所有常见的年、月表述格式,匹配不到时对应数值默认设为0,自动适配单一年份、单一月份、年月共存三种场景
import re

def text_format(text: str) -> int:
    # 匹配年份数字:支持xyears、x years、x year等格式,忽略大小写
    year_match = re.search(r'(\d+)\s*year', text, re.IGNORECASE)
    year = int(year_match.group(1)) if year_match else 0
    # 匹配月份数字:支持xmon、x mon、x mon.、x month等格式,忽略大小写
    month_match = re.search(r'(\d+)\s*mon', text, re.IGNORECASE)
    month = int(month_match.group(1)) if month_match else 0
    return year * 12 + month

测试用例1:Employment period \n2years 2 mon. → 输出26,符合预期
测试用例2:Employment period \n3years → 输出36,符合预期
测试用例3:Employment period 11 mon. → 输出11,符合预期

额外兼容特性:支持数字和单位之间有空格/无空格的排版,适配不同网页的格式差异,大小写混乱的表述也能正常识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:54:04