我正在使用以下代码解析 xml 文件:
import lxml
file_name = input('Enter the file name, including .xml extension: ')
print('Parsing ' + file_name)
from lxml import etree
parser = lxml.etree.XMLParser()
tree = lxml.etree.parse(file_name, parser)
root = tree.getroot()
nsmap = {'xmlns': 'urn:tva:metadata:2010'}
with open(file_name+'.log', 'w', encoding='utf-8') as f:
for info in root.xpath('//xmlns:ProgramInformation', namespaces=nsmap):
crid = (info.get('programId'))
titlex = (info.find('.//xmlns:Title', namespaces=nsmap))
title = (titlex.text if titlex != None else 'Missing')
synopsis1x = (info.find('.//xmlns:Synopsis[1]', namespaces=nsmap))
synopsis1 = (synopsis1x.text if synopsis1x != None else 'Missing')
synopsis1 = synopsis1.replace('\r','').replace('\n','')
f.write('{}|{}|{}\n'.format(crid, title, synopsis1))
让我们以标题“Přešité bydlení”为例。如果我在解析文件时打印标题,它会按预期出现。然而,当我写出来时,它显示为“PÅ™eÅ¡ité bydlenÔ。
我知道这与编码有关(因为我能够将打印命令更改为使用 UTF-8,并“破坏”输出),但我无法按照我的需要打印书面输出.我查看了编解码器库,但没有成功。在 XML 解析器行中使用 'encoding = "utf-8"' 没有任何区别。
如何将书面输出配置为人类可读?
请您参考如下方法:
我以前遇到过各种各样的麻烦。但解决方案相当简单。在 documentation 中有一章是关于如何用 unicode 读写文件的。 .这Python talk对理解问题也很有启发。 Unicode 可能会很痛苦。如果你开始使用 python 3,它会变得容易得多。
import codecs
f = codecs.open('test', encoding='utf-8', mode='w+')
f.write(u'\u4500 blah blah blah\n')
f.seek(0)
print repr(f.readline()[:1])
f.close()
