Hanzi

Ruby gem for handling common Hanzi operations. Can convert to pinyin with proper tones for common words (other gems tend to fail on simple words), return english translation, or convert between simplified and traditional. Uses cc-cedict for data. Example usage:

Hanzi.load_data # optional to pre-load data.
Hanzi.to_pinyin('走红') # zou3hong2
Hanzi.to_pinyin('簡單') # jian3dan1
Hanzi.to_pinyin('为什么') # wei4shen2me5
Hanzi.to_pinyin('no! 为什么!') # no! wei4shen2me5!
Hanzi.to_pinyin('你好, 我是康昱辰。') # ni3hao3, wo3shi4kang1yu4chen2。

Hanzi.to_english('孔子') # Confucius (551-479 BC), Chinese thinker and social philosopher, also known as 孔夫子[Kong3 fu1 zi3]
Hanzi.to_english('老子喜欢') # nil (can only translate exact word matches)

Hanzi.to_traditional('拉萨') # 拉薩
Hanzi.to_traditional('拉薩') # 拉薩
Hanzi.to_simplified('拉薩') # 拉萨
Hanzi.to_simplified('abc 拉萨') # nil (for now, only supports exact word matches)

Hanzi.matching_entries('') # returns an array of the all dict entries with exact hanzi matches
  [{:traditional=>"",
    :simplified=>"",
    :pinyin=>"zhao1",
    :english=>"(chess) move/trick/all right!/(dialect) to add"},
   {:traditional=>"",
    :simplified=>"",
    :pinyin=>"zhao2",
    :english=>
     "to touch/to come in contact with/to feel/to be affected by/to catch fire/to fall asleep/to burn"},
   {:traditional=>"",
    :simplified=>"",
    :pinyin=>"zhe5",
    :english=>"aspect particle indicating action in progress"},
   {:traditional=>"",
    :simplified=>"",
    :pinyin=>"zhuo2",
    :english=>"to wear (clothes)/to contact/to use/to apply"}]

To run tests:

rake test

There is a script for profiling:

ruby test/profile_speed.rb # generates output in /tmp

Contributing to hanzi

  • Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet.

  • Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it.

  • Fork the project.

  • Start a feature/bugfix branch.

  • Commit and push until you are happy with your contribution.

  • Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright © 2013 Steve Jackson. See LICENSE.txt for further details. Uses cc-cedict.org for data.