【问题标题】:Python throws ascii codec can't encode when parsing xmlPython 在解析 xml 时抛出 ascii 编解码器无法编码
【发布时间】:2016-07-03 08:58:07
【问题描述】:

我在 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>

我该如何解决?

【问题讨论】:

  • 请注意,引发异常的是f.write() 行。这里的问题不是 XML 解析,而是写入导致问题的文本文件。 f.write(u'Zolt\xe1n') 会给你同样的错误。

标签: python xml unicode


【解决方案1】:

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')

【讨论】:

  • 当我这样做时,我收到另一个错误消息“for country in findall(article) Syntax error:invalid syntax”
  • @SAMAHA:你没有关闭前一行中的 ) 括号。
  • :该错误已解决。但出现另一个错误说“f.write(name) write() argument 1 must be unicode,not str”
  • 我的python版本是2.7
  • @SAMAHA:对,所有其他写入也必须是 unicode;使用u','u'\n'。我会更新的。
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 2016-10-03
  • 2015-11-06
  • 2011-06-29
  • 1970-01-01
  • 2017-05-30
  • 2011-09-26
  • 1970-01-01
相关资源
最近更新 更多