0

Unicode 文字列を含むファイルがあります。u"L'\xe9quipe le quotidien"

Windowsからエクスポートされiso-8859-1、同じ文字列でエンコードされた別のファイルがあります:(これは私のシェル"L'<E9>quipe le quotidien"からのコピー/貼り付けです)。less

Windows ファイルの内容を で変換すると、Windows ファイルの内容とdecode('iso-8859-1').encode('utf8')は異なる文字列になります: L'équipe le quotidien.

この比較を行う最良の方法は何ですか? latin1 文字列を utf-8 に変換できないようです。

4

1 に答える 1

5

Your file is not encoded to Latin-1 (iso-8859-1). You created a Mojibake instead; if interpreted as a Unicode string I had to encode back to Latin-1 then decode as UTF-8 instead:

>>> print u"L'équipe le quotidien.".encode('latin1').decode('utf8')
L'équipe le quotidien.

Generally speaking, you'd decode both files to unicode objects before comparing. Even then, you can still run into issues with Combining Diacritical Marks, where the letter é is actually represented with two codepoints, U+0065 LATIN SMALL LETTER E and U+0301 COMBINING ACUTE ACCENT.

You can work around that up to a point by normalising the text; pick one of decomposed or composed and normalise both strings to the same form; use the unicodedata.normalize() function. See Normalizing Unicode for more details on that.

于 2015-03-20T16:02:07.973 に答える