バイトストリングでエンコードをミックスしています。この問題を再現する簡単な実例があります。
#!python2
# coding: utf-8
from xml.etree import ElementTree as et
name_element = et.Element('data')
name_element.text = u'Naturalne mydło odświeżające'
name = et.tostring(name_element,encoding='cp852', method='text')
print name
print name.replace('ł', 'l')
出力(代替はありません)::で、name
文字列がcp852
でエンコードされた
理由が、私はあなたがcp852
のエンコーディングにそのデフォルトはWindowsコンソールで実行されていると仮定しますバイト文字列定数'ł'
は、utf-8
のソースコードエンコードでエンコードされています。
print repr(name)
print repr('ł')
出力:
'Naturalne myd\x88o od\x98wie\xbeaj\xa5ce'
'\xc5\x82'
最善の解決策は、Unicode文字列を使用することです:
#!python2
# coding: utf-8
from xml.etree import ElementTree as et
name_element = et.Element('data')
name_element.text = u'Naturalne mydło odświeżające'
name = et.tostring(name_element,encoding='cp852', method='text').decode('cp852')
print name
print name.replace(u'ł', u'l')
print repr(name)
print repr(u'ł')
出力(交換が行われた):
Naturalne mydło odświeżające
Naturalne mydlo odświeżające
u'Naturalne myd\u0142o od\u015bwie\u017caj\u0105ce'
u'\u0142'
注Pythonの3のことet.tostring
にはUnicodeオプションがあり、文字列定数はデフォルトでUnicodeです。文字列のrepr()
バージョンも同様に読みやすいですが、ascii()
は古い動作を実装しています。また、Python 3.6がポーランド語のコードページを使用しないコンソールにもポーランド語を印刷することになるので、文字をまったく置き換える必要はありません。
#!python3
# coding: utf-8
from xml.etree import ElementTree as et
name_element = et.Element('data')
name_element.text = 'Naturalne mydło odświeżające'
name = et.tostring(name_element,encoding='unicode', method='text')
print(name)
print(name.replace('ł','l'))
print(repr(name),repr('ł'))
print(ascii(name),ascii('ł'))
出力:
Naturalne mydło odświeżające
Naturalne mydlo odświeżające
'Naturalne mydło odświeżające' 'ł'
'Naturalne myd\u0142o od\u015bwie\u017caj\u0105ce' '\u0142'
あなたは同じ[標準形](https://en.m.wikipedia.org/wiki/Unicode_equivalence)に両方の文字列のUnicodeの形を正規化する必要があります。 –
[unicodedata.normalize(form、unistr)がどのようにしてどのように動作するかをsomoneで説明できますか?](https://stackoverflow.com/questions/14682397/can-somone-explain-how-unicodedata-normalizeform-unistr-work -with-examples) –