LoginSignup
1
2

More than 5 years have passed since last update.

pythonで漢数字をアラビア数字に変更する

Posted at

漢数字をアラビア数字に変換する必要があり、ググってみたもののピンとくるものがなかったので書いてみた。
["〇","一","二","三","四","五","六","七","八","九"].index("五")が5となることを利用したアルゴリズムである。リストの内部の順序に依存している点で結合度が高いプログラムではあるが、比較的短めに書ける点が利点である。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

KANJI1=["〇","一","二","三","四","五","六","七","八","九"]
KANJI2=["〇","十","百","千"]
KANJI3=["〇","万","億","兆"]

def lessthan10000(string):
    ans = 0
    for k2 in KANJI2[-1:0:-1]:
        if not k2 in string:
            continue
        k1,string = string.split(k2)
        ans += KANJI1.index(k1) * (10**KANJI2.index(k2))
        if not string:
            break
    if string:
        ans += KANJI1.index(string)
    return ans

def morethan10000(string):
    ans = 0
    for k3 in KANJI3[-1:0:-1]:
        if not k3 in string:
            continue
        over, string = string.split(k3)
        ans += lessthan10000(over)*(10**(4*KANJI3.index(k3)))
        if not string:
            break
    if string:
        ans += lessthan10000(string)
    return ans

string = "三十五兆八千億四百二十一万三千三百二十二"
print(morethan10000(string))

懸念点:
「壱」等の文字には対応していないが、多少の修正で対応できると思われる。
lessthan10000とmorethan10000とに共通のコードが多く含まれているのが気持ち悪い。この辺うまく書けそうだがうまい手が思いつかない。

1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2