我已經讀過很多有關Python字符串中反斜槓轉義(以及Python中不同編碼中的反斜槓識別)以及在正則表達式中使用反斜槓的問題,但仍無法解決我的問題。我非常感謝任何幫助(鏈接,代碼示例等)。Python:用字典中的實體替換某些Unicode實體
我想用字典中的某些元素替換字符串中的十六進制代碼,使用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(文本)並設置re.UNICODE,但在我的情況下,這並沒有幫助。
我正在使用Python 2.7.2。
該問題可以找到哪些解決方案?
編輯:
其實我已經通過應用下面的編碼找到了一個可能的解決了這一問題上StandardEncodings和PythonUnicodeIntegration到輸入:
text.encode('unicode_escape')
還有什麼呢?
[\\] u [0-9a-fA-F] {,4}!= [\\] u [0-9a-fA-F] { 0,4} – FailedDev
對不起,逗號不應該在那裏:[\\] u [0-9a-fA-F] {4} – npobedina
你可以簡單地發佈最小數量的可能的代碼來重現輸入字符串和期望的輸出? – FailedDev