20
26

More than 5 years have passed since last update.

# Python で漢数字をアラビア数字に変換

Last updated at Posted at 2015-10-28

ググってみるとあまりサンプルがないし古い (Python2版) のばかりなので作ってみました。
(バグってたので修正)

``````import re

tt_ksuji = str.maketrans('一二三四五六七八九〇壱弐参', '1234567890123')

re_suji = re.compile(r'[十拾百千万億兆\d]+')
re_kunit = re.compile(r'[十拾百千]|\d+')
re_manshin = re.compile(r'[万億兆]|[^万億兆]+')

TRANSUNIT = {'十': 10,
'拾': 10,
'百': 100,
'千': 1000}
TRANSMANS = {'万': 10000,
'億': 100000000,
'兆': 1000000000000}

def kansuji2arabic(kstring: str, sep=False):
"""漢数字をアラビア数字に変換"""

def _transvalue(sj: str, re_obj=re_kunit, transdic=TRANSUNIT):
unit = 1
result = 0
for piece in reversed(re_obj.findall(sj)):
if piece in transdic:
if unit > 1:
result += unit
unit = transdic[piece]
else:
val = int(piece) if piece.isdecimal() else _transvalue(piece)
result += val * unit
unit = 1

if unit > 1:
result += unit

return result

transuji = kstring.translate(tt_ksuji)
for suji in sorted(set(re_suji.findall(transuji)), key=lambda s: len(s),
reverse=True):
if not suji.isdecimal():
arabic = _transvalue(suji, re_manshin, TRANSMANS)
arabic = '{:,}'.format(arabic) if sep else str(arabic)
transuji = transuji.replace(suji, arabic)
elif sep and len(suji) > 3:
transuji = transuji.replace(suji, '{:,}'.format(int(suji)))

return transuji
``````

``````   kansuji2arabic('平成二十七年度予算額１〇億３５００万千百六十4円', True)
'平成27年度予算額1,035,001,164円'
``````
20
26
0

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
20
26