相关疑难解决方法(0)

为什么我们不应该在py脚本中使用sys.setdefaultencoding("utf-8")?

我见过很少的py脚本在脚本的顶部使用它.在什么情况下应该使用它?

import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Run Code Online (Sandbox Code Playgroud)

python encoding utf-8 python-2.x sys

158
推荐指数
3
解决办法
18万
查看次数

sys.setdefaultencoding('utf-8')的危险

sys.setdefaultencoding('utf-8')在Python 2中存在令人沮丧的设置趋势.任何人都可以列出问题的真实例子吗?论证喜欢it is harmfulit hides bugs听起来不太令人信服.

更新:请注意,这个问题只是关于utf-8,它不是关于改变默认编码"一般情况下".

如果可以,请举一些代码示例.

python encoding utf-8 python-2.x

33
推荐指数
3
解决办法
2万
查看次数

BeautifulSoup findall with class attribute- unicode encode error

我使用BeautifulSoup从黑客新闻中提取新闻报道(只是标题)并且到目前为止还有这么多 -

import urllib2
from BeautifulSoup import BeautifulSoup

HN_url = "http://news.ycombinator.com"

def get_page():
    page_html = urllib2.urlopen(HN_url) 
    return page_html

def get_stories(content):
    soup = BeautifulSoup(content)
    titles_html =[]

    for td in soup.findAll("td", { "class":"title" }):
        titles_html += td.findAll("a")

    return titles_html

print get_stories(get_page()
Run Code Online (Sandbox Code Playgroud)

)

但是,当我运行代码时,它会出现错误 -

Traceback (most recent call last):
  File "terminalHN.py", line 19, in <module>
    print get_stories(get_page())
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 131: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我如何让它工作?

python beautifulsoup

6
推荐指数
1
解决办法
2万
查看次数

标签 统计

python ×3

encoding ×2

python-2.x ×2

utf-8 ×2

beautifulsoup ×1

sys ×1