gpt4 book ai didi

Python解析xml时抛出ascii编解码器无法编码

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:55 24 4
gpt4 key购买 nike

我在 Python 中运行以下代码:

import xml.etree.ElementTree as ET
tree = ET.parse('dplp_11.xml')
root = tree.getroot()
f = open('workfile', 'w')
for country in root.findall('article'):
rank = country.find('year').text
name = country.find('title').text

if(int(rank)>2009):
f.write(name)
auth = country.findall('author')
for a in auth:
#print str(a)
f.write(a.text)
f.write(',')
f.write('\n')

我收到一个错误:

Traceback (most recent call last):
File "parser.py", line 14, in <module>
f.write(a.text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128)

我试图解析如下所示的 dblp 数据:

<?xml version="1.0"?>
<dblp>
<article mdate="2011-01-11" key="journals/acta/Saxena96">
<author>Sanjeev Saxena</author>
<title>Parallel Integer Sorting and Simulation Amongst CRCW Models.</title>
<pages>607-619</pages>
<year>1996</year>
<volume>33</volume>
<journal>Acta Inf.</journal>
<number>7</number>
<url>db/journals/acta/acta33.html#Saxena96</url>
<ee>http://dx.doi.org/10.1007/BF03036466</ee>
</article>
<article mdate="2015-07-14" key="journals/acta/BozapalidisFR12">
<author>Symeon Bozapalidis</author>
<author>Zoltán Fülöp 0001</author>
<author>George Rahonis</author>
<title>Equational weighted tree transformations.</title>
<pages>29-52</pages>
<year>2012</year>
<volume>49</volume>
<journal>Acta Inf.</journal>
<number>1</number>
<ee>http://dx.doi.org/10.1007/s00236-011-0148-5</ee>
<url>db/journals/acta/acta49.html#BozapalidisFR12</url>
</article>
</dblp>

如何解决?

最佳答案

a.text 是一个 Unicode 对象,但您试图将其写入普通的 Python 2 文件对象:

f.write(a.text)

f.write() 方法仅接受 byte 字符串(类型 str),触发对 ASCII 编解码器的隐式编码,如果文本无法编码为 ASCII,则触发异常。

您需要使用可以对数据进行编码的编解码器对其进行显式编码,或者使用 io.open() 文件对象来为您进行编码。

显式编码为 UTF-8 可以,例如:

f.write(a.text.encode('utf8'))

或使用带有显式编码的io.open():

import io

# ...

f = io.open('workfile', 'w', encoding='utf8')

之后对 f.write() 的所有调用必须是 Unicode 对象;在任何文字字符串前添加 u 前缀:

for a in auth:
f.write(a.text)
f.write(u',')
f.write(u'\n')

关于Python解析xml时抛出ascii编解码器无法编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com