Total Pageviews

Friday, 17 January 2014

终于解决在一些基于python的静态博客程序里,不能成功发表中文文章的问题

 未做如下设置时,在一些基于python的静态博客程序里,试图发表中文文章时,会遇到:

UnicodeDecodeError: 'ascii' codec can't decode byte...

 
as3:/usr/local/lib/python2.7/site-packages# nano sitecustomize.py
as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8  
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')
as3:/usr/local/lib/python2.7/site-packages#

let me have a check:
as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec  6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'utf8'
>>>
the above shows the default encoding of python is utf8.then the error is no more.
参考http://shirley-ren.iteye.com/blog/1018750

在google上搜了半天,也没搜到什么有用之物,在百度上搜索(国人的文章),却找到了解决之道。看来还是百度更懂中国人

这样,我在http://briteming.blogspot.co.uk/2014/01/linux-vpspython-wok.html里面说的“暂时未能成功发布中文贴”的问题已解决。

python3 区分了 unicode str 和 byte arrary,并且默认编码不再是 ascii。
-------------------------------------------

Python 设置系统的默认编码

python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),python没办法处理非ascii编码的,此时需要自己设置将python的默认编码,一般设置为utf8的编码格式。
查询系统默认编码可以在解释器中输入以下命令:
Python代码  收藏代码
  1. >>>sys.getdefaultencoding()  
设置默认编码时使用:
Python代码  收藏代码
  1. >>>sys.setdefaultencoding('utf8')  
 可能会报AttributeError: 'module' object has no attribute 'setdefaultencoding'的错误,执行reload(sys),在执行以上命令就可以顺利通过。
此时在执行sys.getdefaultencoding()就会发现编码已经被设置为utf8的了,但是在解释器里修改的编码只能保证当次有效,在重启解释器后,会发现,编码又被重置为默认的ascii了,那么有没有办法一次性修改程序或系统的默认编码呢。

有2种方法设置python的默认编码:
一个解决的方案在程序中加入以下代码:
Python代码  收藏代码
  1. import sys  
  2. reload(sys)  
  3. sys.setdefaultencoding('utf8')   
 另一个方案是在python的Lib\site-packages文件夹下新建一个sitecustomize.py,内容为:
Python代码  收藏代码
  1. # encoding=utf8  
  2. import sys  
  3.   
  4. reload(sys)  
  5. sys.setdefaultencoding('utf8')   
此时重启python解释器,执行sys.getdefaultencoding(),发现编码已经被设置为utf8的了,多次重启之后,效果相同,这是因为系统在python启动的时候,自行调用该文件,设置系统的默认编码,而不需要每次都手动的加上解决代码,属于一劳永逸的解决方法.
from http://shirley-ren.iteye.com/blog/1018750
--------------
Python 在某些冷门系统下,中文显示乱码解决
import locale
locale.setlocale(locale.LC_ALL, '')