1

文字コードがshift-jisのバイトデータを、utf-8に変換したいのですが、
変換できない文字が含まれており、どのように変換すればよいか分かりませんでした。
例えば外字の「①」は、以下のようにすることで「(1)」に変換することができましたが、
「(1)」ではなく、utf-8の「①」に変換するにはどうしたらよいでしょうか?

byte_date = b'abc\x82\xa0\x82\xa2\x82\xa4\x87\x40'  # ← shift_jisの「abcあいう①」
byte_date = byte_date.replace(b'\x87\x40', b'(1)')  # \x87\x40は、shift_jisの①
text = byte_date.decode(encoding='shift_jis', errors='replace')  # errors='replace'は不要?
print(text)

以下は、上記コードを実行した結果です。

abcあいう(1)

以下のように変換されることを期待しています。

abcあいう①

[追記]
以下の方法で、期待どおりの結果がえられました。

byte_date = b'abc\x82\xa0\x82\xa2\x82\xa4\x87\x40'  # ← shift_jisの「abcあいう①」
text = byte_date.decode(encoding='cp932')
print(text)
3

1 件の回答 1

2

質問の内容は、encodingをcp932にすれば解決しますが、「utf-8に変換できないshift-jisの文字(環境依存文字)を、個別に変換する方法」(質問文の例のように「(1)」にするなど)としては、codecs.register_errorで自前のエラーハンドラを登録して処理する方法もあります。

# coding: utf-8

import codecs

byte_date = b'abc\x82\xa0\x82\xa2\x82\xa4\x87\x40'  # ← shift_jisの「abcあいう①」
def decode_error(exc):
    encoding, text, start, end, msg = exc.args
    if text[start:start+2] == b'\x87\x40':
        return '(1)', start + 2
    raise exc
codecs.register_error('my_error', decode_error)
text = byte_date.decode(encoding='shift_jis', errors='my_error')
print(text)

この質問に回答するには、ログインする必要があります。