【发布时间】:2017-11-01 19:07:32
【问题描述】:
我正在使用xmlcharrefreplace 替换字符串中的非标准字符,以便可以将其保存在 xml 文件中。后来,我想把这个字符串重新转换回原来的字符。
import openpyxl
import cgi
from html.parser import HTMLParser
parser = HTMLParser()
startingString = "Tỉnh Đồng Nai" #example string
print("Starting string: " + startingString) #Starting string: Tỉnh Đồng Nai
# 1. This string contains non-standard characters. Convert these characters using xmlcharrefreplace
escapedString = cgi.escape(startingString)
strEscapedString = str(escapedString)
aposString = strEscapedString.replace("'", "'")
savedToExcelString = str(aposString.encode('utf-8', 'xmlcharrefreplace') )[2:-1]
print("xmlcharrefreplace converted to: " + savedToExcelString) #xmlcharrefreplace converted to: T\xe1\xbb\x89nh \xc4\x90\xe1\xbb\x93ng Nai
# 2. The string is saved to an xml file
# 3. The string is read from an xml file
# 4. Convert the string back into the original starting string
unescapedString = parser.unescape(savedToExcelString)
#what do I do here??? I need to 'undo' the xmlcharrefreplace encoding
print(startingString + " == " + unescapedString + " is " + str(startingString == unescapedString))
# Tỉnh Đồng Nai == T\xe1\xbb\x89nh \xc4\x90\xe1\xbb\x93ng Nai is False
# ^^ Should be the same string at the end
请注意,我不能使用 codecs.open(),因为我正在使用库 openpyxl 打开包含数据的 Excel 文件。输入可以是什么字符集没有限制 - 我希望最终字符串与初始字符串相同。
目标:将 xmlcharrefreplace 中的字符转换回其脚本字符。 例如:“\x90”变成“ồ”
【问题讨论】:
标签: python xml string decode encode