如何使用python获取原始字符?

2024-04-24 13:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用lxml的etree制作一个个人rss阅读器,但是在转换回原始字符时遇到了困难。我期待看到“2014年世界杯:在乔利奥·塞萨尔的帮助下”:

url = 'rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'
xml = etree.parse(url)
for x in xml.findall('.//item'):
    text = x.find('.//description').text
    print text
    # 'World Cup 2014: With J\xfalio C\xe9sar\u2019s Help'
    text = text.encode('utf-8')
    print text
    # 'World Cup 2014: With J\xfalio C\xe9sar\u2019s Help'
    text = text.decode('utf-8')
    # Error: 'UnicodeEncodeError: 'ascii' codec can't encode character....'

我读了Python's Unicode HOWTO和{a2},但我一定遗漏了什么。在

编辑:几乎有很多感谢unutbu…只需要帮助转换\u2019:

^{pr2}$

Tags: texturlworldwithhelpxmlutfencode
2条回答

在一个字符串中混合了拉丁语-1(\xfa)和Unicode(\u2019)。Python编码方法不能处理这个问题。在

就在UnicodeEncodeError之前,我相信textunicode

text = u'World Cup 2014: With J\xfalio C\xe9sar\u2019s Help'
text = text.decode('utf-8')

复制错误消息:

^{pr2}$

在Python中,lxml sometimes returns ^{} for text, and sometimes ^{}。 实际上,如果运行此脚本,您将看到这种不幸的行为:

import lxml.etree as ET
import urllib2

url = 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'
xml = ET.parse(urllib2.urlopen(url))
for x in xml.findall('.//item'):
    text = x.find('.//description').text
    print(type(text))

印刷品

<type 'str'>
<type 'str'>
<type 'str'>
<type 'unicode'>
<type 'str'>
<type 'unicode'>
...

但是,当文本由纯ASCII值(即0到127之间的字节值)组成时,它只返回str。在

编码{cd4{a>一般不应该由cd4}组成 使用utf-8的0-127(ASCII)范围内的字节值保留str。在

所以你实际上可以用相同的方式来处理str和{},用utf-8编码这两个,就好像{}总是unicode。在

由于text实际上是HTML,下面我使用lxml.html将HTML缩减为纯文本内容。它也可以是strunicode。然后在打印之前对该对象text进行编码:

import lxml.etree as ET
import lxml.html as LH
import urllib2

url = 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'
xml = ET.parse(urllib2.urlopen(url))
for x in xml.findall('.//item'):
    content = x.find('.//description').text
    html = LH.fromstring(content)
    text = html.text_content()
    print(text.encode('utf-8'))

请注意,在Python3中,lxml始终返回unicode,因此思想的纯洁性得以恢复。在


UnicodeEncodeError是如何发生的:

text = u'World Cup 2014: With J\xfalio C\xe9sar\u2019s Help'
text = text.decode('utf-8')
# Error: 'UnicodeEncodeError: 'ascii' codec can't encode character....'

首先请注意,这是一个UnicodeEncodeError,即使您要求Python解码text。 进一步注意,错误消息说Python正在尝试使用ascii编解码器。在

这是一个典型的迹象,表明问题与Python2's automatic conversion between ^{} and ^{}.有关

假设text是unicode。如果你打电话

text.decode('utf-8')

然后要求Python对unicode执行no-no解码。不过,Python2试图适应您的需求,在使用utf-8解码之前,先使用ascii编解码器对unicode进行静默编码。这种str和{}之间的自动转换是为了方便只在ASCII范围内处理str和unicode,但它使精神上的不一致性成为可能,因为它鼓励程序员忘记str和unicode之间的区别,而且它有时只在值在ASCII范围内时有效。当值不在ASCII范围内时,会出现一个错误,这就是您遇到的情况。在

在Python3中,bytes和{}之间没有自动转换(或者Python2的说法分别是{}和{})。当您试图编码bytes或解码str时,Python只会引发一个错误。以迫使程序员注意类型为代价,恢复了心智的清晰性。然而,正如这个问题所表明的,即使是Python,这一成本也是无法避免的。在

相关问题 更多 >