python显示当前中文日期_python自动提取文本中的时间(包含中文日期)
有时在处理不规则数据时需要提取文本包含的时间日期。
dateutil.parser模块可以统一日期字符串格式。
datefinder模块可以在字符串中提取日期。
datefinder模块实现也是用正则,功能很全 但是对中文不友好。
但是这两个模块都不能支持中文及一些特殊的情况;所以我用正则写了段代码可进行中文日期及一些特殊的时间识别
例如:
'2012年12月12日','3小时前','在2012/12/13哈哈','时间2012-12-11 12:22:30','日期2012-13-11','测试2013.12.24','今天12:13'
import re
import chardet
from datetime import datetime,timedelta
# 匹配正则表达式
matchs = {
1:(r'\d{4}%s\d{1,2}%s\d{1,2}%s \d{1,2}%s\d{1,2}%s\d{1,2}%s','%%Y%s%%m%s%%d%s %%H%s%%M%s%%S%s'),
2:(r'\d{4}%s\d{1,2}%s\d{1,2}%s \d{1,2}%s\d{1,2}%s','%%Y%s%%m%s%%d%s %%H%s%%M%s'),
3:(r'\d{4}%s\d{1,2}%s\d{1,2}%s','%%Y%s%%m%s%%d%s'),
4:(r'\d{2}%s\d{1,2}%s\d{1,2}%s','%%y%s%%m%s%%d%s'),
# 没有年份
5:(r'\d{1,2}%s\d{1,2}%s \d{1,2}%s\d{1,2}%s\d{1,2}%s','%%m%s%%d%s %%H%s%%M%s%%S%s'),
6:(r'\d{1,2}%s\d{1,2}%s \d{1,2}%s\d{1,2}%s','%%m%s%%d%s %%H%s%%M%s'),
7:(r'\d{1,2}%s\d{1,2}%s','%%m%s%%d%s'),
# 没有年月日
8:(r'\d{1,2}%s\d{1,2}%s\d{1,2}%s','%%H%s%%M%s%%S%s'),
9:(r'\d{1,2}%s\d{1,2}%s','%%H%s%%M%s'),
}
# 正则中的%s分割
splits = [
{1:[('年','月','日','点','分','秒'),('-','-','',':',':',''),('\/','\/','',':',':',''),('\.','\.','',':',':','')]},
{2:[('年','月','日','点','分'),('-','-','',':',''),('\/','\/','',':',''),('\.','\.','',':','')]},
{3:[('年','月','日'),('-','-',''),('\/','\/',''),('\.','\.','')]},
{4:[('年','月','日'),('-','-',''),('\/','\/',''),('\.','\.','')]},
{5:[('月','日','点','分','秒'),('-','',':',':',''),('\/','',':',':',''),('\.','',':',':','')]},
{6:[('月','日','点','分'),('-','',':',''),('\/','',':',''),('\.','',':','')]},
{7:[('月','日'),('-',''),('\/',''),('\.','')]},
{8:[('点','分','秒'),(':',':','')]},
{9:[('点','分'),(':','')]},
]
def func(parten,tp):
re.search(parten,parten)
parten_other = '\d+天前|\d+分钟前|\d+小时前|\d+秒前'
class TimeFinder(object):
def __init__(self,base_date=None):
self.base_date = base_date
self.match_item = []
self.init_args()
self.init_match_item()
def init_args(self):
# 格式化基础时间
if not self.base_date:
self.base_date = datetime.now()
if self.base_date and not isinstance(self.base_date,datetime):
try:
self.base_date = datetime.strptime(self.base_date,'%Y-%m-%d %H:%M:%S')
except Exception as e:
raise 'type of base_date must be str of%Y-%m-%d %H:%M:%S or datetime'
def init_match_item(self):
# 构建穷举正则匹配公式 及提取的字符串转datetime格式映射
for item in splits:
for num,value in item.items():
match = matchs[num]
for sp in value:
tmp = []
for m in match:
tmp.append(m%sp)
self.match_item.append(tuple(tmp))
def get_time_other(self,text):
m = re.search('\d+',text)
if not m:
return None
num = int(m.group())
if '天' in text:
return self.base_date - timedelta(days=num)
elif '小时' in text:
return self.base_date - timedelta(hours=num)
elif '分钟' in text:
return self.base_date - timedelta(minutes=num)
elif '秒' in text:
return self.base_date - timedelta(seconds=num)
return None
def find_time(self,text):
# 格式化text为str类型
if isinstance(text,bytes):
encoding =chardet.detect(text)['encoding']
text = text.decode(encoding)
res = []
parten = '|'.join([x[0] for x in self.match_item])
parten = parten+ '|' +parten_other
match_list = re.findall(parten,text)
if not match_list:
return None
for match in match_list:
for item in self.match_item:
try:
date = datetime.strptime(match,item[1].replace('\\',''))
if date.year==1900:
date = date.replace(year=self.base_date.year)
if date.month==1:
date = date.replace(month=self.base_date.month)
if date.day==1:
date = date.replace(day=self.base_date.day)
res.append(datetime.strftime(date,'%Y-%m-%d %H:%M:%S'))
break
except Exception as e:
date = self.get_time_other(match)
if date:
res.append(datetime.strftime(date,'%Y-%m-%d %H:%M:%S'))
break
if not res:
return None
return res
def test():
timefinder =TimeFinder(base_date='2020-04-23 00:00:00')
for text in ['2012年12月12日','3小时前','在2012/12/13哈哈','时间2012-12-11 12:22:30','日期2012-13-11','测试2013.12.24','今天12:13']:
res = timefinder.find_time(text)
print('text----',text)
print('res---',res)
if __name__ == '__main__':
test()
测试运行结果如下
text---- 2012年12月12日
res--- ['2012-12-12 00:00:00']
text---- 3小时前
res--- ['2020-04-22 21:00:00']
text---- 在2012/12/13哈哈
res--- ['2012-12-13 00:00:00']
text---- 时间2012-12-11 12:22:30
res--- ['2012-12-11 12:22:30']
text---- 日期2012-13-11
res--- None
text---- 测试2013.12.24
res--- ['2013-12-24 00:00:00']
text---- 今天12:13
res--- ['2020-04-23 12:13:00']
python显示当前中文日期_python自动提取文本中的时间(包含中文日期)相关推荐
- python时间模块提取时间_【转载】python自动提取文本中的时间(包含中文日期)...
import re import chardet from datetime import datetime,timedelta # 匹配正则表达式 matchs = { 1:(r'\d{4}%s\d ...
- 时间语义解析工具 Python版,从文本中提取时间,并解析其含义,在线使用,时间语义识别
时常我们需要从文本中,提取出时间信息,并将这个信息标准化,例如: [新华社报2021-9-9]国家统计局今天发布了2021年8月份全国CPI(居民消费价格指数) 需要从中抽取出 2021-9-9 和 ...
- 自然语言处理(NLP)之从文本中提取时间
在我们的日常生活和工作中,从文本中提取时间是一项非常基础却重要的工作,因此,接下来将介绍如何从文本中有效地提取时间. 举个简单的例子,我们需要从下面的文本中提取时间: 6月28日,杭州市统计局权威 ...
- SpringBoot中文文档 SpringBoot中文参考指南 SpringBoot中文参考文档 springboot中文文档 springboot中文
SpringBoot中文文档 SpringBoot中文参考指南 SpringBoot中文参考文档 springboot中文文档 springboot中文 SpringBoot中文文档 SpringBo ...
- python 英语词频统计软件_Python数据挖掘——文本分析
作者 | zhouyue65 来源 | 君泉计量 文本挖掘:从大量文本数据中抽取出有价值的知识,并且利用这些知识重新组织信息的过程. 一.语料库(Corpus) 语料库是我们要分析的所有文档的集合. ...
- python爬虫中文乱码_Python 爬虫过程中的中文乱码问题
python+mongodb 在爬虫的过程中,抓到一个中文字段,encode和decode都无法正确显示 注:以下print均是在mongodb中截图显示的,在pythonshell中可能会有所不同 ...
- python单词个数统计_Python 统计文本中单词的个数
1.读文件,通过正则匹配 def statisticWord(): line_number = 0 words_dict = {} with open (r'D:\test\test.txt',enc ...
- python中文聊天_Python下两种曲线救国实现AIML中文聊天机器人功能的方法
alicebot.jpg AIML,全称Artificial Intelligence Markup Language,是一种XML模式,用做自然语言聊天机器人的规则库. 最简单的AIML规则如下: ...
- python输出文本和值_python读取文本中数据并转化为DataFrame的实例
在技术问答中看到一个这样的问题,感觉相对比较常见,就单开一篇文章写下来. 从纯文本格式文件 "file_in"中读取数据,格式如下: 需要输出成"file_out&quo ...
最新文章
- SilverLight 一日两次碰壁
- debian编译mysql_MySQL数据库之Debian 6.02下编译安装 MySQL 5.5的方法
- 关于索引的相关 day45
- void类型和void *的用法
- 绝望:对不完的数,加不完的班
- @Size注解无法使用
- Google Chrome 开发进度 官方Blog
- openwrt路由器samba拒绝访问
- 马克思主义基本原理【0163】
- C语言获取当前的工作路径
- 浙大版《C语言程序设计实验与习题指导(第4版)》题目集-编程题-实验1-1-Hello World!
- 淘宝API item_search_jupage - 天天特价
- 什么是蜘蛛池的搜索留痕技术
- 计算机通电后自动断电,电脑开机自动断电,详细教您电脑开机自动断电怎么解决...
- python符号计算 漂亮地打印出来_让Python输出更漂亮:PrettyPrinter
- python 英语分词_NLTK(一):英文分词分句
- 「DaoCloud 道客」郭峰:云原生加速金融信创发展
- windows7声卡驱动修复压缩包
- 微信小程序上传头像先裁剪图片后上传
- 40岁程序员遭劝退找不到工作,大龄码农注定被淘汰?
热门文章
- 从语言模型到Seq2Seq:Transformer如戏,全靠Mask
- 能量视角下的GAN模型(二):GAN=“分析”+“采样”
- 大家心目中的这些「优质」论文,你读过几篇?| PaperDaily #01
- HDU 2612 Find a way bfs
- 三星a7支持html吗,三星A7怎么样 三星A7特点介绍
- (第二篇)Vue计算属性、侦听器、过滤器
- java: -source 1.5 中不支持 diamond 运算符 (请使用 -source 7 或更高版本以启用 diamond 运算符)
- 编程式事务控制相关对象
- eclipse安装lombok后无法启动解决办法
- jQuery给输入框绑定键盘事件