最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python自動提取文本中的時間(包含中文日期)

 更新時間:2020年08月31日 09:50:44   作者:古月月月胡  
這篇文章主要介紹了python自動提取文本中的時間(包含中文日期),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

有時在處理不規(guī)則數(shù)據(jù)時需要提取文本包含的時間日期。

dateutil.parser模塊可以統(tǒng)一日期字符串格式。

datefinder模塊可以在字符串中提取日期。

datefinder模塊實現(xiàn)也是用正則,功能很全 但是對中文不友好。

但是這兩個模塊都不能支持中文及一些特殊的情況;所以我用正則寫了段代碼可進行中文日期及一些特殊的時間識別

例如:

'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):
    # 格式化基礎(chǔ)時間
    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):
    # 構(gòu)建窮舉正則匹配公式 及提取的字符串轉(zhuǎn)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()

測試運行結(jié)果如下

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']

 到此這篇關(guān)于python自動提取文本中的時間(包含中文日期)的文章就介紹到這了,更多相關(guān)python自動提取時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中pinyin庫實現(xiàn)漢字轉(zhuǎn)換為拼音

    Python中pinyin庫實現(xiàn)漢字轉(zhuǎn)換為拼音

    python-pinyin是一個用于漢字轉(zhuǎn)拼音的Python庫,支持多音字、多種拼音風(fēng)格和自定義詞典,本文就來介紹一下Python中pinyin庫實現(xiàn)漢字轉(zhuǎn)換為拼音,感興趣的可以了解一下
    2025-01-01
  • 在Python程序中實現(xiàn)分布式進程的教程

    在Python程序中實現(xiàn)分布式進程的教程

    這篇文章主要介紹了在Python程序中實現(xiàn)分布式進程的教程,在多進程編程中十分有用,示例代碼基于Python2.x版本,需要的朋友可以參考下
    2015-04-04
  • 利用Python腳本寫端口掃描器socket,python-nmap

    利用Python腳本寫端口掃描器socket,python-nmap

    這篇文章主要介紹了利用Python腳本寫端口掃描器socket,python-nmap,文章圍繞主題展開詳細介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-07-07
  • 學(xué)會這29個常用函數(shù),你就是Pandas專家

    學(xué)會這29個常用函數(shù),你就是Pandas專家

    Pandas?無疑是?Python?處理表格數(shù)據(jù)最好的庫之一,但是很多新手無從下手,這里總結(jié)出最常用的?29?個函數(shù),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-11-11
  • python使用nntp讀取新聞組內(nèi)容的方法

    python使用nntp讀取新聞組內(nèi)容的方法

    這篇文章主要介紹了python使用nntp讀取新聞組內(nèi)容的方法,實例分析了Python操作nntp讀取新聞組內(nèi)容的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • Python使用django獲取用戶IP地址的方法

    Python使用django獲取用戶IP地址的方法

    這篇文章主要介紹了Python使用django獲取用戶IP地址的方法,實例分析了django獲取用戶IP地址過程中出現(xiàn)的問題與對應(yīng)的解決方法,非常簡單實用,需要的朋友可以參考下
    2015-05-05
  • Caffe數(shù)據(jù)可視化環(huán)境python接口配置教程示例

    Caffe數(shù)據(jù)可視化環(huán)境python接口配置教程示例

    這篇文章主要為大家介紹了Caffe數(shù)據(jù)可視化環(huán)境python接口配置教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • Python遍歷numpy數(shù)組的實例

    Python遍歷numpy數(shù)組的實例

    下面小編就為大家分享一篇Python遍歷numpy數(shù)組的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • pycharm不在cmd中運行卻在python控制臺運行問題解決

    pycharm不在cmd中運行卻在python控制臺運行問題解決

    這篇文章主要介紹了pycharm不在cmd中運行卻在python控制臺運行問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08
  • pygame實現(xiàn)時鐘效果

    pygame實現(xiàn)時鐘效果

    這篇文章主要為大家詳細介紹了pygame實現(xiàn)時鐘效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-06-06

最新評論

集贤县| 平阳县| 余江县| 深泽县| 杭州市| 涡阳县| 民权县| 石首市| 红安县| 林周县| 剑阁县| 东安县| 会泽县| 资中县| 邹平县| 凌源市| 博野县| 商洛市| 衡南县| 拜泉县| 金乡县| 满洲里市| 东阳市| 新绛县| 石嘴山市| 松潘县| 荣成市| 东城区| 青州市| 哈巴河县| 布尔津县| 怀化市| 如皋市| 潼关县| 百色市| 和顺县| 勐海县| 二手房| 栖霞市| 皋兰县| 黎城县|