Python プログラムで次の変換 (ソース -> ターゲット) を行う方法を教えてください。
>>> source = '\\x{4e8b}\\x{696d}'
>>> print source
\x{4e8b}\x{696d}
>>> print type(source)
<type 'str'>
>>> target = u'\u4e8b\u696d'
>>> print target.encode('utf-8')
事業
ありがとうございました。
とを使用int
しunichr
てそれらを変換できます。
>>> int('4e8b', 16)
20107
>>> unichr(int('4e8b', 16))
u'\u4e8b'
>>> print unichr(int('4e8b', 16))
事
Blender のアイデアを利用して、呼び出し可能な置換引数でre.subを使用できます。
import re
def touni(match):
return unichr(int(match.group(1), 16))
source = '\\x{4e8b}\\x{696d}'
print(re.sub(r'\\x\{([\da-f]+)\}', touni, source))
収量
事業
import re
p = re.compile(r'[\W\\x]+')
print ''.join([unichr(int(y, 16)) for y in p.split(source) if y != ''])
事業
また、@Blenderからアイデアを盗みました...