【问题标题】:ElementTree will not parse special characters with Python 2.7ElementTree 不会使用 Python 2.7 解析特殊字符
【发布时间】:2026-01-16 10:50:01
【问题描述】:

我不得不将我的 python 脚本从 python 3 重写为 python2,之后我在使用 ElementTree 解析特殊字符时遇到了问题。

这是我的一段xml:

<account number="89890000" type="Kostnad" taxCode="597" vatCode="">Avsättning egenavgifter</account>

这是我解析这一行时的输出:

('account:', '89890000', 'AccountType:', 'Kostnad', 'Name:', 'Avs\xc3\xa4ttning egenavgifter')

所以看来是字符“ä”的问题。

这就是我在代码中的做法:

sys.setdefaultencoding( "UTF-8" )
xmltree = ET()

xmltree.parse("xxxx.xml")

printAccountPlan(xmltree)

def printAccountPlan(xmltree):
    print("account:",str(i.attrib['number']),      "AccountType:",str(i.attrib['type']),"Name:",str(i.text))

任何人都有一个ide来让ElementTree解析字符“ä”,所以结果会是这样的:

('account:', '89890000', 'AccountType:', 'Kostnad', 'Name:', 'Avsättning egenavgifter')

【问题讨论】:

    标签: python python-2.7 elementtree


    【解决方案1】:

    您同时遇到了 Python 2 和 Python 3 之间的两个独立差异,这就是您得到意外结果的原因。

    第一个区别是您可能已经知道的:Python 版本 2 中的 print 语句在版本 3 中变成了 print 函数。这种变化在您的情况下产生了一种特殊情况,稍后我会谈到.但简而言之,这是“打印”工作方式的不同之处:

    在 Python 3 中:

    >>> # Two arguments 'Hi' and 'there' get passed to the function 'print'.
    >>> # They are concatenated with a space separator and printed.
    >>> print('Hi', 'there') 
    >>> Hi there
    

    在 Python 2 中:

    >>> # 'print' is a statement which doesn't need parenthesis.
    >>> # The parenthesis instead create a tuple containing two elements 
    >>> # 'Hi' and 'there'. This tuple is then printed.
    >>> print('Hi', 'there')
    >>> ('Hi', 'there')
    

    您的第二个问题是元组通过在每个元素上调用 repr() 来打印自己。在 Python 3 中,repr() 会根据需要显示 unicode。但在 Python 2 中,repr() 对任何超出可打印 ASCII 范围(例如,大于 127)的字节值使用转义字符。这就是你看到它们的原因。

    您可以决定是否解决此问题,具体取决于您的代码目标。 Python 2 中元组的表示使用转义字符,因为它不是为向最终用户显示而设计的。这更多是为了您作为开发人员的内部便利,用于故障排除和类似任务。如果您只是为自己打印它,那么您可能不需要更改任何内容,因为 Python 向您显示该非 ASCII 字符的编码字节正确地存在于您的字符串中。如果您确实想向最终用户显示具有元组外观格式的内容,那么一种方法(保留正确的 unicode 打印)是手动创建格式,如下所示:

    def printAccountPlan(xmltree):
        data = (i.attrib['number'], i.attrib['type'], i.text)
        print "('account:', '%s', 'AccountType:', '%s', 'Name:', '%s')" % data
    # Produces this:
    # ('account:', '89890000', 'AccountType:', 'Kostnad', 'Name:', 'Avsättning egenavgifter')
    

    【讨论】:

    • 作为补充说明,这似乎不是 ElementTree 如何解析特殊字符的问题,而是关于如何让 Python 以所需方式显示它们的问题。