2009-08-25 22 views
4

こんにちは私はPythonで問題があります。私は私の問題を例で説明しようとしています。python - 正規表現とユニコードの問題

私は、この文字列を持っている:

>>> string = 'ÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' 
>>> print string 
ÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà 

を、私が試してみました、例えば、 "" と私

をN、A、異なるcharachtersを置き換えたい:

>>> rePat = re.compile('[^ÑÃï]',re.UNICODE) 
>>> print rePat.sub("",string) 
������������������������������������������������à 

私はこれを得た。 私はこれが起こっていると思うのは、このタイプの文字列がベクトルの2つの位置で表現されているからです。たとえば\ xc3 \ x91 =Ñです。 これに対して、私がregolar式を作成すると、すべての\ xc3は置き換えられません。どのように私はこのタイプのサブ?????あなたの文字列がUnicode文字列ではなく、プレーンな文字列(プレーン文字列はバイト配列のようなもの)であることを確認する必要があり

おかげ フランコ

答えて

14

例:

>>> string = 'ÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' 
>>> type(string) 
<type 'str'> 

# do this instead: 
# (note the u in front of the ', this marks the character sequence as a unicode literal) 
>>> string = u'\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\xc0\xc1\xc2\xc3' 
# or: 
>>> string = 'ÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ'.decode('utf-8') 
# ... but be aware that the latter will only work if the terminal (or source file) has utf-8 encoding 
# ... it is a best practice to use the \xNN form in unicode literals, as in the first example 

>>> type(string) 
<type 'unicode'> 
>>> print string 
ÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà 

>>> rePat = re.compile(u'[^\xc3\x91\xc3\x83\xc3\xaf]',re.UNICODE) 
>>> print rePat.sub("", string) 
à 

ファイルからの読み込み、string = open('filename.txt').read()はバイトシーケンスを読み込みます。

ユニコードのコンテンツを取得するには、string = unicode(open('filename.txt').read(), 'encoding')を実行します。または:string = open('filename.txt').read().decode('encoding')

codecsモジュールは、オンザフライでユニコードストリーム(ファイルなど)をデコードできます。

python unicodeのGoogle検索を実行します。 PythonのUnicode処理は、最初は理解するのが難しいかもしれません。

私はこのルールに従っています。「ソフトウェアは、Unicode文字列で内部的にしか動作せず、出力時に特定のエンコーディングに変換する必要があります。 (http://www.amk.ca/python/howto/unicodeから)

私もお勧めします:http://www.joelonsoftware.com/articles/Unicode.html