【问题标题】:python ET.tostring(root, encoding='Unicode', method='xml') raise TypeError: a bytes-like object is required, not 'str'python ET.tostring(root, encoding='Unicode', method='xml') raise TypeError: a bytes-like object is required, not 'str'
【发布时间】:2017-04-25 13:34:32
【问题描述】:

有人知道为什么这段代码没问题:

text='''<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>'''
root=ET.fromstring(text)
ET.tostring(root, method='xml')
ET.tostring(root, encoding='UTF-8', method='xml')

但是当我使用 Unicode 编码时: ET.tostring(root, encoding='Unicode', method='xml')

我明白了:

 Traceback (most recent call last):
  ... omissis ...
  File "/home/ago/anaconda3/lib/python3.6/xml/etree/ElementTree.py", line 915, in _serialize_xml
    write("<" + tag)
TypeError: a bytes-like object is required, not 'str'

TypeError: a bytes-like object is required, not 'str'

根据带有 tostring 的 python 3.6 doc 我可以使用 'Unicode' ...

"使用 encoding="unicode" 生成一个 Unicode 字符串(否则,一个 bytestring 生成)。”

我可以毫无问题地使用ElementTree.write(... encoding='Unicode' ...)

我用:

Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 12:22:00) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux

Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux

我有不同的行为:

ET.tostring(root, encoding='Unicode')
Traceback (most recent call last):
  ... omissis ...
  File "/usr/lib/python3.4/xml/etree/ElementTree.py", line 917, in _serialize_xml
    write("<" + tag)
TypeError: 'str' does not support the buffer interface

提前致谢

【问题讨论】:

  • 如果您使用encoding='unicode'(小写“u”),错误就会消失,不是吗?
  • 宾果游戏!感谢 mzjn,我误读了我在问题中引用的内容:“使用 encoding="unicode" 生成 Unicode 字符串(否则会生成一个字节串)。” ... ElementTree.write() 使用enc_lower = encoding.lower() 降低字符串。即使 tostring 似乎调用 ElementTree.write,它的工作方式也不同。我将深入研究 ET 代码...

标签: python elementtree


【解决方案1】:

'Unicode' 不是有效编码,因为它不是编码而是一系列代码点(请参阅utf-8 vs unicode)。

Python 3 以 Unicode 格式存储字符串,因此要使其成为 bytes-like object,首先需要对其进行编码(例如编码为 utf-8)。

ElementTree.fromstring 需要使用特定编码而不是 Unicode 编码的 bytes-like object

附带说明一下,相反的做法是采用 bytes-like object 并使用 bytes-like object 的编码解码为 Unicode。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 2018-02-19
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2020-01-30
    相关资源
    最近更新 更多