Skip to main content
 首页 » 编程设计

Python:用字典中的实体替换某些 Unicode 实体

2025年05月04日9zfyouxi

我已经阅读了很多关于 python 字符串中反斜杠转义的问题(以及不同编码的 Python 中的反斜杠识别)以及在正则表达式中使用反斜杠的问题,但仍然无法解决我的问题。我将非常感谢任何帮助(链接、代码示例等)。

我正在尝试使用 re 将字符串中的十六进制代码替换为字典中的某些元素。代码是 '\uhhhh' 类型,其中 hhhh 是十六进制数。

我从 sqlite3 表中选择字符串;默认情况下,它们被读取为 unicode 而不是“原始”unicode 字符串。

import re 
pattern_xml = re.compile(r""" 
(.*?)                        
([\\]u[0-9a-fA-F]{4}) 
(.*?)                            
""", re.VERBOSE | re.IGNORECASE | re.DOTALL) 
uni_code=['201C','201D'] 
decoded=['"','"'] 
def repl_xml(m): 
    item=m.group(2) 
    try: decodeditem=decoded[uni_code.index(item.lstrip('\u').upper())] 
    except: decodeditem=item 
    return m.group(1) + "".join(decodeditem) + m.group(3) 
 
#input         
text = u'Try \u201cquotated text should be here\u201d try' 
#text after replacement 
decoded_text=pattern_xml.subn(repl_xml,text)[0] 
#desired outcome 
desired_text=u'Try "quotated text should be here" try' 

所以,我希望 _decoded_text_ 等于 _desired_text_。

我没有成功用双反斜杠替换单个反斜杠或强制 python 将文本视为原始 unicode 字符串(这样反斜杠被按字面意思处理,而不是像转义字符)。我也尝试过使用 re.escape(text) 并设置 re.UNICODE,但对我来说没有帮助。
我正在使用 Python 2.7.2。

这个问题有哪些解决方案?

编辑:
我实际上已经在 StandardEncodings 上找到了解决这个问题的可能方法。和 PythonUnicodeIntegration通过将以下编码应用于输入:

text.encode('unicode_escape') 

还有什么事要做吗?

请您参考如下方法:

示例文本不包含任何反斜杠。 \u201c 只是一种表示 unicode 字符的方式:

>>> text = u'Try \u201cquotated text should be here\u201d try' 
>>> '\\' in text 
False 
>>> print text 
Try “quotated text should be here” try 

这里并不需要正则表达式。只需根据需要翻译目标 unicode 字符:

>>> table = {0x201c: u'"', 0x201d: u'"'} 
>>> text.translate(table) 
u'Try "quotated text should be here" try'