Ruby: 中文解析时间

Ruby: Parse time in Chinese

时间是这样的2016年4月27日(年月日)

什么是解析它的好方法?

我想我可以逃过一劫

  time = '2016年4月27日'
  year = time.split('年')[0]

然后重新整理时间。不过这也涉及到encoding utf-8的东西,我不是很熟悉

1.9.3-p551 :001 > r   = /(\d+)年(\d+)月(\d+)日/
 => /(\d+)年(\d+)月(\d+)日/
1.9.3-p551 :002 > s = '2016年4月27日'
 => "2016年4月27日"
1.9.3-p551 :003 > m = r.match(s)
 => #<MatchData "2016年4月27日" 1:"2016" 2:"4" 3:"27">
1.9.3-p551 :004 > m.to_a
 => ["2016年4月27日", "2016", "4", "27"]
1.9.3-p551 :005 > yr, mo, da = m[1..-1]
 => ["2016", "4", "27"]
1.9.3-p551 :006 > yr
 => "2016"
1.9.3-p551 :007 > mo
 => "4"
1.9.3-p551 :008 > da
 => "27"

假设 '2016年4月27日' 是您的输入字符串并且您希望从中得到一个 Date 对象,因为您知道字符串的每个组成部分代表什么,您可以使用 Date.strptime 和传入格式字符串:

irb> date = Date.strptime("2016年4月27日", "%Y年%m月%d日")
=> #<Date: 2016-04-27 ((2457506j,0s,0n),+0s,2299161j)>
irb> date.year
=> 2016
irb> date.month
=> 4
irb> date.day
=> 27 
  • You dont have to write RE string by yourself.
  • JioNLP a Python package provide a wide range of chinese parser like the following examples:

安装 Installation

  • python>=3.6 github 版本略领先于 pip
$ git clone https://github.com/dongrixinyu/JioNLP
$ cd ./JioNLP
$ pip install .

pip 安装

pip install jionlp

  • jio.parse_time 给定时间字符串,解析其为时间戳、时长等。
import time
import jionlp as jio
res = jio.parse_time('今年9月', time_base={'year': 2021})
res = jio.parse_time('零三年元宵节晚上8点半', time_base=time.time())
res = jio.parse_time('一万个小时')
res = jio.parse_time('100天之后', time.time())
res = jio.parse_time('每周五下午4点', time.time())
print(res)

# {'type': 'time_span', 'definition': 'accurate', 'time': ['2021-09-01 00:00:00', '2021-09-30 23:59:59']}
# {'type': 'time_point', 'definition': 'accurate', 'time': ['2003-02-15 20:30:00', '2003-02-15 20:30:59']}
# {'type': 'time_delta', 'definition': 'accurate', 'time': {'hour': 10000.0}}
# {'type': 'time_span', 'definition': 'blur', 'time': ['2021-10-22 00:00:00', 'inf']}
# {'type': 'time_period', 'definition': 'accurate', 'time': {'delta': {'day': 7}, 
#  'point': {'time': ['2021-07-16 16:00:00', '2021-07-16 16:59:59'], 'string': '周五下午4点'}}}