Skip to content

Commit

Permalink
增加连续数字的解析
Browse files Browse the repository at this point in the history
  • Loading branch information
qhwa committed Mar 17, 2014
1 parent 6a74427 commit de6e3ba
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 4 deletions.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -28,6 +28,9 @@ You can use the top-level api:
~~~ruby
ChinseNumber.trans "我有十块钱"
#=> "我有10块钱"

ChinseNumber.trans "二〇一四年"
#=> "2014年"
~~~

or use the standalone parser:
Expand Down
4 changes: 2 additions & 2 deletions chinese_number.gemspec
Expand Up @@ -8,8 +8,8 @@ Gem::Specification.new do |spec|
spec.version = ChineseNumber::VERSION
spec.authors = ["qhwa"]
spec.email = ["qhwa@163.com"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.summary = %q{Translate Chinese numbers into Arabic numbers}
spec.description = %q{This ruby gem translate Chinse numbers into Arabic numbers. e.g. “一十” => 10.}
spec.homepage = ""
spec.license = "MIT"

Expand Down
10 changes: 9 additions & 1 deletion lib/chinese_number/parser.rb
Expand Up @@ -34,6 +34,14 @@ def self.generate_multipers_map
TOKEN = Regexp.new( "[#{(DIGIT_MAP.keys + MULTIPERS.keys).join}]+" )

def parse word

raise InvalidWord unless word =~ /\A#{TOKEN}\Z/

# 类似“二零一二” 这种短语,可以直接拼数字返回
unless word =~ MULTIPER_TOKEN
return word.gsub(/\S/) {|w| DIGIT_MAP[w]}.to_i
end

@scanner = StringScanner.new( word )
parts = []

Expand Down Expand Up @@ -83,7 +91,7 @@ def to_i
end
end

class UnexpectToken < RuntimeError
class InvalidWord < RuntimeError
end

end
Expand Down
8 changes: 7 additions & 1 deletion spec/parser_spec.rb
Expand Up @@ -6,6 +6,12 @@
@parser = ChineseNumber::Parser.new
end

it '可以解析连续的数字' do
test '一二三', 123
test '二零一二', 2012
test '二〇一二', 2012
end

it '可以解析个位数字' do
test '零', 0
test '〇', 0
Expand Down Expand Up @@ -82,7 +88,7 @@
it '对于不合法的文字抛出错误' do
expect {
@parser.parse('没有数字').should
}.to raise_error( ChineseNumber::Parser::UnexpectToken )
}.to raise_error( ChineseNumber::Parser::InvalidWord )
end

def test word, expect_digit
Expand Down

0 comments on commit de6e3ba

Please sign in to comment.