Created
February 2, 2012 02:25
-
-
Save aita/1720989 to your computer and use it in GitHub Desktop.
数値のルビ生成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding:utf-8 | |
from StringIO import StringIO | |
RUBY_LIST = ( | |
(100, u"ひゃく"), | |
(10, u"じゅう"), | |
(9, u"きゅう"), | |
(8, u"はち"), | |
(7, u"なな"), | |
(6, u"ろく"), | |
(5, u"ご"), | |
(4, u"よん"), | |
(3, u"さん"), | |
(2, u"に"), | |
(1, u"いち"), | |
(0, u"ぜろ"), | |
) | |
def number_to_ruby(num, ruby_list=RUBY_LIST): | |
u""" | |
貪欲法による数値のルビの生成器 | |
>>> ruby = number_to_ruby(1) | |
>>> ruby == u"いち" | |
True | |
>>> ruby = number_to_ruby(39) | |
>>> ruby == u"さんじゅうきゅう" | |
True | |
>>> ruby = number_to_ruby(74) | |
>>> ruby == u"ななじゅうよん" | |
True | |
""" | |
ruby_dict = dict(ruby_list) | |
out = StringIO() | |
if num == 0: | |
out.write(ruby_dict[0]) | |
while num: | |
for n, ruby in ruby_dict: | |
if num < n: | |
continue | |
m = num / n | |
if m > 1: | |
out.write(number_to_ruby(m)) | |
out.write(ruby) | |
num = num % n | |
break | |
return out.getvalue() | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment