Module: PinYin
- Defined in:
- lib/ruby-pinyin.rb,
lib/ruby-pinyin/value.rb,
lib/ruby-pinyin/version.rb
Defined Under Namespace
Classes: Value
Constant Summary collapse
- VERSION =
'0.2.1'
Class Method Summary collapse
- .abbr(str, except_lead = false, except_english = true) ⇒ Object
- .codes ⇒ Object
- .of_string(str, tone = nil, include_punctuations = false) ⇒ Object
- .override_files ⇒ Object
- .override_files=(files) ⇒ Object
- .permlink(str, sep = '-') ⇒ Object
- .punctuations ⇒ Object
- .sentence(str, tone = nil) ⇒ Object
Class Method Details
.abbr(str, except_lead = false, except_english = true) ⇒ Object
64 65 66 67 68 69 70 71 |
# File 'lib/ruby-pinyin.rb', line 64 def abbr(str, except_lead=false, except_english=true) result = "" of_string(str).each_with_index do |word, i| w = (except_lead && i == 0) || (except_english && word.english?) ? word : word[0] result << w end result end |
.codes ⇒ Object
15 16 17 18 19 20 21 22 23 24 |
# File 'lib/ruby-pinyin.rb', line 15 def codes return @codes if @codes @codes = {} src = File.('../ruby-pinyin/Mandarin.dat', __FILE__) override_files.unshift(src).each do |file| load_codes_from(file) end @codes end |
.of_string(str, tone = nil, include_punctuations = false) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/ruby-pinyin.rb', line 36 def of_string(str, tone=nil, include_punctuations=false) res = [] return res unless str && !str.empty? str.unpack('U*').each_with_index do |t,idx| code = sprintf('%x',t).upcase readings = codes[code] if readings res << Value.new(format(readings, tone), false) else val = [t].pack('U*') if val =~ /^[_0-9a-zA-Z\s]*$/ # 复原,去除特殊字符,如全角符号等。 (res.last && res.last.english? ? res.last : res) << Value.new(val, true) # 如果上一个字符也是非中文则与之合并 elsif include_punctuations val = [punctuations[code]].pack('H*') if punctuations.has_key?(code) (res.last ? res.last : res) << Value.new(val, false) end end end res.map {|phrase| phrase.split(/\s+/)}.flatten end |
.override_files ⇒ Object
6 7 8 |
# File 'lib/ruby-pinyin.rb', line 6 def override_files @override_files || [] end |
.override_files=(files) ⇒ Object
10 11 12 13 |
# File 'lib/ruby-pinyin.rb', line 10 def override_files=(files) @override_files = files @codes = nil end |
.permlink(str, sep = '-') ⇒ Object
60 61 62 |
# File 'lib/ruby-pinyin.rb', line 60 def permlink(str, sep='-') of_string(str).join(sep) end |
.punctuations ⇒ Object
26 27 28 29 30 31 32 33 34 |
# File 'lib/ruby-pinyin.rb', line 26 def punctuations return @punctuations if @punctuations @punctuations = {} src = File.('../ruby-pinyin/Punctuations.dat', __FILE__) load_punctuations_from(src) @punctuations end |
.sentence(str, tone = nil) ⇒ Object
73 74 75 |
# File 'lib/ruby-pinyin.rb', line 73 def sentence(str, tone=nil) of_string(str, tone, true).join(' ') end |