私は使用されているタイトルはわかりませんが、基本的には文字列から奇妙な文字を取り除きたいと思っています。ここでは、コードは次のようになります。Python文字エンコーディング?
#!/usr/bin/python
# -*- coding: utf-8 -*-
# source: http://snippets.dzone.com/posts/show/4569
from htmlentitydefs import name2codepoint as n2cp
import re
def substitute_entity(match):
ent = match.group(3)
if match.group(1) == "#":
if match.group(2) == '':
return unichr(int(ent))
elif match.group(2) == 'x':
return unichr(int('0x'+ent, 16))
else:
cp = n2cp.get(ent)
if cp:
return unichr(cp)
else:
return match.group()
def decode_htmlentities(string):
entity_re = re.compile(r'&(#?)(x?)(\d{1,5}|\w{1,8});')
return entity_re.subn(substitute_entity, string)[0]
test = ['<b>Blogger</b> in the Classroom - <b>Google</b>', 'Of\xef\xac\x81cial <b>Google Blog</b>']
container = []
for i in test:
container.append(decode_htmlentities(i))
print container
for i in test:
print decode_htmlentities(i)
そして、ここではその結果です:
['<b>Blogger</b> in the Classroom - <b>Google</b>', 'Of\xef\xac\x81cial <b>Google Blog</b>']
<b>Blogger</b> in the Classroom - <b>Google</b>
Official <b>Google Blog</b>
質問:同じ機能を使用して
(decode_htmlentities())、追加するとき、私は別の結果を得る理由リストと 'ちょうど'の印刷に?ここで
が違いです:
Of\xef\xac\x81cial <b>Google Blog</b> # output from list
Official <b>Google Blog</b> # output from print
あなたは、特殊文字に対してあなたの正規表現をテストしましたか? – PenguinCoder
いいえ、私はそれをテストしていません。印刷とリストの追加の結果が異なるのはなぜですか? – kholidfu
pythonでリスト項目を印刷すると、実際のリスト自体を印刷するのとは異なった解釈が行われます。ジョシュ・リーの答えを見てください。 – PenguinCoder