2007-08-16

[メモ]Pythonによる英字の半角全角変換

↓これもっと簡潔できれいな書き方はないものだろうか。

from itertools import izip
#半角英字->全角英字変換
HAN_CHARS = map(chr, range(ord('A'), ord('Z')+1) + range(ord('a'), ord('z')+1))
ZEN_CHARS = map(lambda x: unichr(0xff00 + x),range(0x21, 0x21+ord('Z')-ord('A')+1) +
range(0x41, 0x41+ord('Z')-ord('A')+1))
def han2zen(word):
"""
Unicodeで与えられた文字列の半角英字を全角英字に変換する。
"""
for c, cc in izip(HAN_CHARS, ZEN_CHARS):
word = word.replace(c, cc)
return word



追記----
多少ましなものになった
import re
HAN_UPPER = re.compile(u"[A-Z]")
HAN_LOWER = re.compile(u"[a-z]")
def han2zen(word):
word = HAN_UPPER.sub(lambda m: unichr(ord(u"A") + ord(m.group(0)) - ord("A")), word)
word = HAN_LOWER.sub(lambda m: unichr(ord(u"a") + ord(m.group(0)) - ord("a")), word)
return word


追記----
調子に乗って一般化してみた。上のような変換関数を大量生産できる関数だ。
Unicodeの列を平行移動するようなイメージの変換を生成します。
#!/usr/bin/python
# _*_ coding: euc_jp _*_
import re

def replace_sequence(*transform_rules):
"""
Unicode文字コードで連続した文字の列を対応する別の連続する文字に変換する関数を作る。

引数:
transform_rules 変換ルールを表す文字列を任意個の引数で与える。
一つの変換ルールは3文字のUnicode文字で表現されます。

変換ルール記述例
u"AZA" 一文字目は変換元の文字列の先頭、二文字目は変換元文字列の末尾、三文字目は変換先文字列の先頭を表します。

この変換ルールを引数に並べます。

"""
rules = map(lambda x: (re.compile(u"[%s-%s]" % tuple(x[:2])), x[2], x[0]), transform_rules)
def henkan(word):
for pattern, start, src_start in rules:
word = pattern.sub(lambda m: unichr(ord(start) + ord(m.group(0)) - ord(src_start)), word)
return word
return henkan

if __name__ == "__main__":
num_han2zen = replace_sequence(u"090")
num_zen2han = replace_sequence(u"090")
alpha_han2zen = replace_sequence(u"AZA", u"aza")
alpha_zen2han = replace_sequence(u"AZA", u"aza")

print num_han2zen(u"0120-116")
print num_zen2han(u"188−0013")
print alpha_han2zen(u"ABCを習いました。")
print alpha_zen2han(u"世界のSONY")

この関数replace_sequenceを使うと、上で必死こいてつくってた半角英字->全角英字関数はこの一行で作成できる。

alpha_han2zen = replace_sequence(u"AZA", u"aza")

使う時はこのalpha_han2zenを関数として呼び出し、

print alpha_han2zen(u"ABCを習いました。")

で行ける。

上のプログラムの実行結果。
ayu@~/work% ./sample.py
0120-116
188−0013
ABCを習いました。
世界のSONY

これはちょっと便利かも。会社に持っていこう。
こういうプログラムを書いていると、今更関数型言語を勉強しなくても、Pythonで、まあいいのかなという気にもなり、またしても自分の進歩が阻害されてしまう気がする。