この文字列を変換したい
foo_utf = u'nästy chäräctörs with å and co.' # unicode
これに
foo_ascii = 'nästy chäräctörs with å and co.' # ASCII
.
Python(2.6)でこれを行う方法はありますか?unicodedataモジュールを見つけましたが、変換方法がわかりません。
この文字列を変換したい
foo_utf = u'nästy chäräctörs with å and co.' # unicode
これに
foo_ascii = 'nästy chäräctörs with å and co.' # ASCII
.
Python(2.6)でこれを行う方法はありますか?unicodedataモジュールを見つけましたが、変換方法がわかりません。
私はあなたができるとは思わない。これらの「厄介な文字」は ASCII としてエンコードできないため、別のエンコード (UTF-8 または Latin-1 または Windows-1252 など) を選択する必要があります。
codecs
Python の stdlib のモジュールには、拡張文字をどのように処理するかに応じて、いくつかのオプションがあります。
>>> import codecs
>>> u = u'nästy chäräctörs with å and co.'
>>> encode = codecs.get_encoder('ascii')
>>> encode(u)
'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128)
>>> encode(u, 'ignore')
('nsty chrctrs with and co.', 31)
>>> encode(u, 'replace')
('n?sty ch?r?ct?rs with ? and co.', 31)
>>> encode(u, 'xmlcharrefreplace')
('nästy chäräctörs with å and co.', 31)
>>> encode(u, 'backslashreplace')
('n\\xe4sty ch\\xe4r\\xe4ct\\xf6rs with \\xe5 and co.', 31)
うまくいけば、それらの1つがあなたのニーズを満たすでしょう。詳細については、Python コーデック モジュールのドキュメントを参照してください。
encode
文字列の方法を試してください。
>>> u'nästy chäräctörs with å and co.'.encode('latin-1')
'n\xe4sty ch\xe4r\xe4ct\xf6rs with \xe5 and co.'
Pythonで提供されているunicodedataモジュール(http://docs.python.org/library/unicodedata.html)を使用して、多くのユニコード値をAsciiバリアントに変換することもできます。IEは、さまざまな「」などを修正します。その後、encode()メソッドを実行すると、文字列を完全にクリーンアップできます。
主にunicodedataから何を取得するかを正規化して、NFKCフラグを渡す方法。
これは実際には Django に関する質問であり、python に関する質問ではありません。文字列が .py ファイルの 1 つにある場合は、ファイルの先頭に次の行があることを確認してください。
-*- coding: utf-8 -*-
さらに、文字列は「unicode」(u'foobar') 型である必要があります。
次に、HTML ページが Unicode で動作することを確認します。
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
それはすべてのトリックを行う必要があります。エンコード/デコードなどは必要ありません。すべてがユニコードであることを確認してください。安全な側にいます。