python - ElementTree 和 unicode

标签 python unicode encoding utf-8 elementtree

我在一个 xml 文件中有这个字符:

<data>
  <products>
      <color>fumè</color>
  </product>
</data>

我尝试使用以下代码生成 ElementTree 的实例:

string_data = open('file.xml')
x = ElementTree.fromstring(unicode(string_data.encode('utf-8')))

我收到以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 185: ordinal not in range(128)

(注意:位置不准确,我是从一个较大的 xml 中采样的)。

如何解决?谢谢

最佳答案

您可能在使用 Requests (HTTP for Humans) 时偶然发现了这个问题, response.text 默认解码响应,你可以使用 response.content 来获取未解码的数据,这样 ElementTree 就可以自己解码了。请记住使用正确的编码。

更多信息:http://docs.python-requests.org/en/latest/user/quickstart/#response-content

关于python - ElementTree 和 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12349728/

相关文章:

Python:在文件中查找正则表达式

python - 错误 : command 'gcc' failed with exit status 1 on centos 6. 5

python - pandas DataFrame.query 表达式,默认返回所有行

java - 有人可以澄清 Gson 的 unicode 编码吗?

python - 如何使用 py(py)odbc 从 python 连接到远程 MS SQL Server

c++ - 在 Windows 中不使用 Unicode 有什么缺点?

.net - 写一个更好的自然排序(比我的)

xcode - 如何防止在 Unity3d IL2CPP 中剥离托管 dll

C# 使用压缩小数编码 EBCDIC 中的文件

php - 如何从具有特殊编码的单词中获取每个字符