在咱們的平常生活和工做中,從文本中提取時間是一項很是基礎卻重要的工做,所以,本文將介紹如何從文本中有效地提取時間。
舉個簡單的例子,咱們須要從下面的文本中提取時間:python
6月28日,杭州市統計局權威公佈《2019年5月月報》,杭州市醫保參保人數達到1006萬,相比於2月份的989萬,三個月暴漲16萬人參保,傲視新一線城市。
咱們能夠從文本有提取6月28日
,2019年5月
, 2月份
這三個有效時間。
一般狀況下,較好的解決思路是利用深度學習模型來識別文本中的時間,經過必定數量的標記文本和合適的模型。本文嘗試利用現有的NLP工具來解決如何從文本中提取時間。
本文使用的工具爲哈工大的pyltp,能夠在Python的第三方模塊中找到,實現下載好分詞模型cws.model
和詞性標註pos.model
這兩個模型文件。
話很少說,咱們直接上Python代碼,以下:web
# -*- coding: utf-8 -*- import os from pyltp import Segmentor from pyltp import Postagger class LTP(object): def __init__(self): cws_model_path = os.path.join(os.path.dirname(__file__), 'cws.model') # 分詞模型路徑,模型名稱爲`cws.model` pos_model_path = os.path.join(os.path.dirname(__file__), 'pos.model') # 詞性標註模型路徑,模型名稱爲`pos.model` self.segmentor = Segmentor() # 初始化實例 self.segmentor.load(cws_model_path) # 加載模型 self.postagger = Postagger() # 初始化實例 self.postagger.load(pos_model_path) # 加載模型 # 分詞 def segment(self, text): words = list(self.segmentor.segment(text)) return words # 詞性標註 def postag(self, words): postags = list(self.postagger.postag(words)) return postags # 獲取文本中的時間 def get_time(self, text): # 開始分詞及詞性標註 words = self.segment(text) postags = self.postag(words) time_lst = [] i = 0 for tag, word in zip(postags, words): if tag == 'nt': j = i while postags[j] == 'nt' or words[j] in ['至', '到']: j += 1 time_lst.append(''.join(words[i:j])) i += 1 # 去重子字符串的情形 remove_lst = [] for i in time_lst: for j in time_lst: if i != j and i in j: remove_lst.append(i) text_time_lst = [] for item in time_lst: if item not in remove_lst: text_time_lst.append(item) # print(text_time_lst) return text_time_lst # 釋放模型 def free_ltp(self): self.segmentor.release() self.postagger.release() if __name__ == '__main__': ltp = LTP() # 輸入文本 sent = '6月28日,杭州市統計局權威公佈《2019年5月月報》,杭州市醫保參保人數達到1006萬,相比於2月份的989萬,三個月暴漲16萬人參保,傲視新一線城市。' time_lst = ltp.get_time(sent) ltp.free_ltp() # 輸出文本中提取的時間 print('提取時間: %s' % str(time_lst))
接着,咱們測試幾個例子。算法
輸入文本爲:微信
今天,央行舉行了2019年6月份金融統計數據解讀吹風會,發佈了2019年6月份金融統計數據並就當前的一些熱點問題進行了解讀和迴應。
文本中提取的時間爲:app
提取時間: ['今天', '2019年6月份', '2019年6月份', '當前']
輸入文本爲:工具
2006年,上海的國內生產總值達到10296.97億元,是中國內地第一個GDP突破萬億元的城市。2008年,北京GDP破萬億。兩年後,廣州GDP超過萬億。2011年,深圳、天津、蘇州、重慶4城的GDP也進入了萬億行列。武漢、成都在2014年躋身「萬億俱樂部」,杭州、南京和青島、無錫和長沙的GDP依次在2015年、2016年和2017年過萬億。寧波和鄭州則成爲2018年萬億俱樂部的新成員。
文本中提取的時間爲:post
提取時間: ['2006年', '2008年', '2011年', '2014年', '2015年', '2016年', '2018年']
輸入文本爲:學習
此後,6月28日、7月9日和7月11日下午,武威市政協、市人大、市政府分別召開堅定全面完全肅清火榮貴流毒和影響專題民主生活會。
文本中提取的時間爲:測試
提取時間: ['此後', '6月28日', '7月9日', '7月11日下午']
輸入文本爲:code
姜保紅出生於1974年4月,她於2016年11月至2018年9月任武威市副市長,履新時,武威市的一把手正是火榮貴。
文本中提取的時間爲:
提取時間: ['1974年4月', '2016年11月至2018年9月']
本次分享到此結束,歡迎你們批評指正。
注意:不妨瞭解下筆者的微信公衆號: Python爬蟲與算法(微信號爲:easy_web_scrape), 歡迎你們關注~