2016-10-24 20 views
0

utf-8文字セットを別のutf-8文字セットに置き換えたいが、何か試してみるとエラーが発生する。utf8文字を置換する

私は何を達成したいこと(例の)

トライ(maintananceのために、より読みやすい)Unicode値またはHTMLエンティティで文字を変換しているので、しばらくお待ちください

のPythonでのnoob午前:

1.First

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

#Found this function 
def multiple_replace(dic, text): 
    pattern = "|".join(map(re.escape, dic.keys())) 
    return re.sub(pattern, lambda m: dic[m.group()], text) 

text="Larry Wall is ùm© some text" 
replace_table = { 
    u'\x97' : u'\x82' # ù -> é 
} 
text2=multiple_replace(dic,text) 
print text #Expected:Larry Wall is ém© some text 
      #Got: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal 

2.Htmlエンティティ

dic = { 
    "ú" : "é" # ù -> é 
} 

some_text="Larry Wall is ùm© some text" 
some_text2=some_text.encode('ascii', 'xmlcharrefreplace') 
some_text2=multiple_replace(dic,some_text2) 
print some_text2 
    #Got:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 14: ordinal not in range(128) 

すべてのアイデアは歓迎されている

+0

"UTF-8文字"とは何ですか? –

+0

私はù、Û、ë、ìなどの文字を参照していましたか、何か不足していますか? –

+1

はPython2または3ですか? – danielfranca

答えて

1

あなたの問題は、あなたの入力文字列が非ユニコード表現(<type 'str'>ではなく、<type 'unicode'>)であるという事実によるものです。私はかなり確信しているのに対し、現在はそれprintの入力文字列(text) -

text=u"Larry Wall is ùm© some text" 
# ^

(あなたが最初の例では、最後の文を修正する必要がありますほかに:あなたはu"..."構文を使用して入力文字列を定義する必要がありますあなたは結果(text2)を見ることを意味しました)。

+0

うわー、私は思ったよりも簡単です、ありがとう –

関連する問題