是的,另一个杂乱无章的unicode问题。
我有一个代码片段:
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神奇地工作,在python2.7中实际应该做什么?
例如,我现在正在修复的Django代码中有这个构造:
stuff = StringIO(unicode(request.body))这是坏的和错误的。但是我无法解释为什么它是坏的和错误的,只是说它破坏了许多不是utf-8的编码。
我知道字符串是,在python 3中编码的字符串,python 2.7中的ascii字符串。我知道StringIO让我把字符串当作缓冲区对待。我知道stuff = StringIO(unicode(request.body))会使用导入的unicode_literals,但我不知道为什么我不知道该怎么做才能避免编写大量丑陋的代码来检测Django的request.body编码,这也是我发布这篇文章的原因。
tl;dr
unicode_literals在python2.7中是什么,它会修复stuff = StringIO(unicode(request.body))中的Django错误吗?副作用是什么?
非常感谢
发布于 2016-01-29 09:52:49
unicode文本不会影响像StringIO(unicode(request.body))这样的代码。它所做的就是在Python 2中不使用前缀时更改文字字符串的类型。
没有unicode文本
u'y' # unicode string
b'z' # byte string
'x' # byte string使用unicode文字
from __future__ import unicode_literals
u'y' # unicode string
b'z' # byte string
'x' # *unicode* string当您使用unicode文本时,您的行为与Python相同(不能在Python3.0到3.2中使用3.3+ )。
将request.body从字节字符串转换为unicode字符串的正确方法是在将字节字符串转换为unicode时指定编码。
stuff = StringIO(body.decode('utf-8'))如果编码不是utf-8,则更改编码。
https://stackoverflow.com/questions/35080995
复制相似问题