我目前正在编写一个简短的 Python 脚本来遍历服务器上的一些目录,找到我要查找的内容并将数据保存到 XML 文件中。
问题是一些数据是用其他语言编写的,例如“ハローワールド”或类似格式的东西。当尝试将其保存在 XML 的条目中时,我得到以下回溯:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position 18: ordinal not in range(128)
这就是我保存数据的函数的样子:
def addHistoryEntry(self, title, url):
self.log.info('adding history entry {"title":"%s", "url":"%s"}' % (title, url))
root = self.getRoot()
history = root.find('.//history')
entry = etree.SubElement(history, 'entry')
entry.set('title', title)
entry.set('time', str(unixtime()))
entry.text = url
history.set('results', str(int(history.attrib['results']) + 1))
self.write(root)
self.getRoot()
如下:
def getRoot(self):
return etree.ElementTree(file = self.config).getroot()
这是写入数据的函数 (self.write(root)
)
def write(self, xmlRoot):
bump = open(self.config, 'w+')
bump.write(dom.parseString(etree.tostring(xmlRoot, 'utf-8')).toxml())
bump.close()
进口是:
import xml.etree.ElementTree as etree
import xml.dom.minidom as dom
如果有人可以帮我解决这个问题,请帮忙。 感谢您的帮助。
最佳答案
可以使用python的codecs库,以及.decode('utf-8')来解决。
import sys,codecs
reload(sys)
sys.setdefaultencoding("utf-8")
关于Python 将 unicode 保存到 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24101549/