【发布时间】:2016-01-29 09:29:31
【问题描述】:
是的,另一个漫无边际的 unicode 问题。
我有一个代码sn-p:
from __future__ import unicode_literals
import requests
from lxml import etree
class Review(object):
def __init__(self, site_name):
self.parser = etree.HTMLParser()
# other things
def get_root(self, url):
# snip snip
resp = requests.get(url)
html = resp.text
root = etree.parse(StringIO(html), self.parser)
return root
这行得通。
在 Python 3 中,这将类似于:
from urllib import request
# stuff to detect encoding of page
response = request.urlopen(req)
html = response.read().decode(detected_encoding)
root = etree.parse(StringIO(self.html_doc), self.parser)
当页面声明的编码不是其实际编码时,需要处理大量丑陋的代码。
我的问题是 unicode_literals 对我来说本质上是巫术,我为自己的无知感到尴尬。为什么root = etree.parse(StringIO(html), self.parser) 在大多数中在导入 unicode_literals 的情况下神奇地工作,在 python 2.7 中真正正确的做法是什么?
例如,我现在正在修复的一些 Django 代码中有这个结构:
stuff = StringIO(unicode(request.body))
那是不好的和错误的。但我无法解释为什么它是坏的和错误的,只能说它破坏了 not utf-8
的 许多 编码我知道字符串是在 python 3 中编码的字符串,在 python 2.7 中是 ascii。我知道 StringIO 让我将字符串视为缓冲区。而且我知道stuff = StringIO(unicode(request.body)) 可以使用导入的 unicode_literals request.body,这就是我发布此内容的原因。
tl;博士
python 2.7 中的 unicode_literals 是什么,它会修复 stuff = StringIO(unicode(request.body)) 中的 Django 错误,会有什么副作用?
非常感谢
【问题讨论】:
-
您的基本误解是 Python 3 中的字符串是“带编码的字符串”。不,字符串是 unicode,并且没有编码。
标签: python django python-2.7 unicode