我见过很少的py脚本在脚本的顶部使用它.在什么情况下应该使用它?
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Run Code Online (Sandbox Code Playgroud) sys.setdefaultencoding('utf-8')
在Python 2中存在令人沮丧的设置趋势.任何人都可以列出问题的真实例子吗?论证喜欢it is harmful
或it hides bugs
听起来不太令人信服.
更新:请注意,这个问题只是关于utf-8
,它不是关于改变默认编码"一般情况下".
如果可以,请举一些代码示例.
我使用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)
我如何让它工作?