2017-02-17 48 views
0

我正在使用character.encode("unicode_escape"))函数将Devnagri和其他印度语脚本字符转换为unicode版本,但当涉及到英文alphbets,数字数字和特殊字符时,此功能失败。 任何人都可以为此提出任何其他功能吗?如何将任何语言的字符转换为python中各自的unicode?

+0

一些为例你正在经历的将会是蓖麻使用!粘贴一些代码! – Bodao

+0

你能举个例子吗? '“foo”.encode(“unicode_escape”)'起作用。 – tdelaney

+0

既然它的python和我们正在谈unicode,你可能也想提一下你是否使用2.x或3.x ... –

回答

0

unicode_escape编解码器仅将非ASCII字符转换为Unicode转义格式。但是你可以自己设置其格式:

#!python3.6 
# coding:utf8 
import re 

def escape(s): 
    def replace(m): 
     item = ord(m.group(0)) 
     if item < 0x100: 
      return fr'\x{item:02x}' 
     elif item < 0x10000: 
      return fr'\u{item:04x}' 
     return fr'\U{item:08X}' 
    return re.sub(r'.',replace,s) 

s = 'abcü马克' 
print(escape(s)) 

输出:

\x61\x62\x63\xfc\u9a6c\u514b\U0001F600 

下面是一个Python 2.7(窄版本)换算的...为什么使用Unicode应切换到Python 3人:

#!python2.7 
#coding:utf8 
import re 

def escape(s): 
    def replace(m): 
     char = m.group(0) 
     if len(char) > 1: 
      # Python 2 uses UTF-16 surrogate pairs for Unicode above U+FFFF. 
      # Manually convert a UTF-16 surrogate pair to a Unicode ordinal. 
      item = (((ord(char[0]) & 0x3FF) << 10) | (ord(char[1]) & 0x3FF)) + 0x10000 
     else: 
      item = ord(char) 
     if item < 0x100: 
      return r'\x{:02x}'.format(item) 
     elif item < 0x10000: 
      return r'\u{:04x}'.format(item) 
     return r'\U{:08X}'.format(item) 
    # This regular expression detects UTF-16 surrogate pairs. 
    return re.sub(ur'[\ud800-\udbff][\udc00-\udfff]|.',replace,s) 

s = u'abcü马克' 
print(escape(s)) 

输出(相同):

\x61\x62\x63\xfc\u9a6c\u514b\U0001F600 
+0

OP似乎在Python 2.7上,所以3.6 f-string语法可能没有帮助。 :-) – ShadowRanger

+0

@ShadowRanger OP应该在他的问题中提出这个问题。培训:)无论如何,我看到评论后正在2.7版本。这是一个很好的例子,为什么要切换到Python 3 :) –

+1

没有参数。我可以用Py2做一个可怕的死亡事件,所以我们并不总是用一只手绑在背后编码。 :-) – ShadowRanger

相关问题