背景
OCR识别的字符串中,日期类型存在字符串中,需要提取出来,并格式化
环境以及依赖package
NStudyPy==0.0.12
NStudyPy 工具包 , 一个有用的工具包,可以简化开发流程,详细介绍可以参考 NStudyPy
本教程使用python 3.10.13
作为开发环境 , 原则上适用于python 3.9+
本教程开发环境为windows 10
,原则上其他系统应该也可以 , 但请注意需要安装对应环境的 poppler, 同时需注意配置环境变量
, 环境变量配置请参阅本站其他文档
!!本站支持全文搜索。
主要流程
- 创建项目,安装依赖
pip install NStudyPy==0.0.12
- 调用方法
from NStudyPy import PyDate# 示例日期字符串
date_strs = ['有效2024-06-18', "日期:2024-06-18结束", '2024-06-18有效','日期:2024/06/18', '2024/6/18', '2024年06月18日','日期2024年6月8日', '24年6月8日', '024年6月8日',
]for d in date_strs:print(f"原始日期字符串:{d}\t\t 格式化后字符串:\t\t{PyDate.format_date(d)}")
- 核心源码
_reg_date = re.compile(r'(\d{2,4}).*?(\d{1,2}).*?(\d{1,2})')def format_date(date_str: str) -> str:"""格式化日期字符串:param date_str: 任意包含日期的字符串:return: 格式化后的日期字符串 yyyy-mm-dd日"""match = _reg_date.search(date_str)if match:year, month, day = match.groups()if len(year) == 2:year = '20' + yearelif len(year) == 3:year = '2' + yearreturn f"{year}-{month.zfill(2)}-{day.zfill(2)}"else:return None