2017-12-08 17 views
1

私は問題を示すために簡略化したバージョンを書いています。私はutf-8とUTF-16形式の特殊文字をエンコードしています。Pythonで奇妙な主役utf-8/utf-16エンコーディング

utf-8エンコーディングでは問題はありません。私がUTF-16でエンコーディングしているとき、私は奇妙な先導文字を取得します。

すべての末尾の文字と先頭の文字を削除しようとしましたが、引き続きエラーが発生します。コードの

サンプル:出力の

#!/usr/bin/env python2 
# -*- coding: utf-8 -*- 

import chardet 


def myEncode(s, pattern): 
try: 
    s.strip() 
    u = unicode(s, pattern) 
    print chardet.detect(u.encode(pattern, 'strict')) 
    return u.encode(pattern, 'strict') 
except UnicodeDecodeError as err: 
    return "UnicodeDecodeError: ", err 
except Exception as err: 
    return "ExceptionError: ", err 

print myEncode(r"""Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§""", 
       'utf-8') 
print myEncode(r"""Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§""", 
       'utf-16') 

サンプル:私は間違っているつもりです

{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'} 
Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§ 
{'confidence': 1.0, 'language': '', 'encoding': 'UTF-16'} 
��Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§ 

私はそれを把握することはできません。私はUTF-16をUTF-8に戻したくないので、UTF-16でフォーマットを保持することが重要です。

更新: @tripleeeのおかげで、私の問題の解決策は、エンコードUTF-16leまたはUTF-16beを定義することです。あなたの時間と労力に感謝します。

すべての時間と労力のために事前に感謝します。

+1

は、バイトオーダーマークではないでしょうか? (別名BOM) –

+0

コードのインデントが間違っているので、それを確認してください。コードのブロックをコピー/ペーストし、それを選択してCtrl-Kですべてをインデントすると、通常は良い結果が得られます。 – tripleee

+2

あなたは実際のバイトが何であるかを言っておらず、これがUTF-16leかUTF-16beの場合は指定していません。あなたの端末の文字セットもここでプレイしています。 UTF-16 [BOM](https://en.wikipedia.org/wiki/Byte_order_mark)の実際のバイトは0xff 0xfeになり、その順序はバイト順に依存します。 – tripleee

答えて

0

@tripleeeによって問題が解決されました。

utf-16の代わりにutf-16leまたはutf-16beを定義すると、問題が解決されました。ソリューションの

サンプル:出力の

#!/usr/bin/env python2 
# -*- coding: utf-8 -*- 

import chardet 


def myEncode(s, pattern): 
    try: 
     s.strip() 
     u = unicode(s, pattern) 
     print chardet.detect(u.encode(pattern, 'strict')) 
     return u.encode(pattern, 'strict') 
    except UnicodeDecodeError as err: 
     return "UnicodeDecodeError: ", err 
    except Exception as err: 
     return "ExceptionError: ", err 

print myEncode(r"""Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§""", 
       'utf-8') 
print myEncode(r"""Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§""", 
       'utf-16be') 

サンプル:

{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'} 
Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§ 
{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'} 
Test !"#$%&'()*+-,./:;<=>[email protected][\]?_{@}~& € ÄÖÜ äöüß £¥§ 
関連する問題