eucJP-ms文字列をユニコード文字列に変換する
EUC-JPのMS独自拡張であるeucJP-msの文章を読み込む必要に迫られたのですが、str.decodeメソッドでは、ユニコードに変換できないようなので以下のような関数を自作してみました。
def dec_eucjpms(s): def try_dec(s): try: res = s.decode('euc_jp') except Unic odeDecodeError, val: res += s[:val[2]].decode('euc_jp') res += _table[s[val[2]:val[3]]] return res ,s[val[3]:] else: return res ,"" res = "" while s: (decoded,s) = try_dec(s) res += decoded return res _table = {"\xad\xb5":u"\u2160", "\xad\xb6":u"\u2161", "\xad\xb7":u"\u2162", "\xad\xb8":u"\u2163", "\xad\xb9":u"\u2164", "\xad\xba":u"\u2165", "\xad\xbb":u"\u2166", "\xad\xbc":u"\u2167", "\xad\xbd":u"\u2168", "\xad\xbe":u"\u2169", "\xad\xea":u"\u3231", "\xad\xeb":u"\u3232", "\xad\xa1":u"\u2460", "\xad\xa2":u'\u2461', "\xad\xa3":u'\u2462', "\xad\xa4":u"\u2463", "\xad\xa5":u'\u2464', "\xad\xa6":u'\u2465', "\xad\xa7":u"\u2466", "\xad\xa8":u'\u2467', "\xad\xa9":u'\u2468', "\xad\xaa":u'\u2469'} if __name__ == "__main__": for item in sorted(_table.keys()): print repr(item), dec_eucjpms(item)
変換テーブルはこちらのサイトを参考にしましたが、とりあえず必要だったものしか入れてないので必要に応じて追加して使ってください。テーブルにない文字を変換しようとするとKeyErrorを吐きます。