首页 > 编程语言 >python中文乱码问题大总结

python中文乱码问题大总结

时间:2023-06-11 17:32:00浏览次数:41  
标签:编码 中文 utf python gb2312 乱码 print unicode encode

        在运行这样类似的代码:


#!/usr/bin/env python
s = "中文"
print  s


最近经常遇到这样的问题:


问题一:SyntaxError: Non-ASCII character '\xe4' in file E:\coding\python\Untitled 6.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details


问题二:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 108: ordinal not in range(128)


问题三:UnicodeEncodeError: 'gb2312' codec can't encode character u'\u2014' in position 72366: illegal multibyte sequence


这些都是跟字符编码有关的问题,很郁闷,中文总是弄不出来,找了很多方案,这里有些是我前几天找到的一些方案,拿出来给大家分享一下哈


 字符串在Python内部的表示是unicode 编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。


decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。


encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。


在某些IDE中,字符串的输出总是出现乱码,甚至错误,其实是由于IDE的结果输出控制台自身不能显示字符串的编码,而不是程序本身的问题。


如在UliPad中运行如下代码:


s=u"中文"

print s

会提示:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)。这是因为UliPad在英文WindowsXP 上的控制台信息输出窗口是按照ascii编码输出的(英文系统的默认编码是ascii),而上面代码中的字符串是Unicode编码的,所以输出时产生了错误。


将最后一句改为:print s.encode('gb2312')


则能正确输出“中文”两个字。


若最后一句改为:print s.encode('utf8')


则输出:\xe4\xb8\xad\xe6\x96\x87,这是控制台信息输出窗口按照ascii编码输出utf8编码的字符串的结果。


下面代码可能比较通用一些,如下:


#!/usr/bin/env python  
#coding=utf-8  
s = "中文"
if  isinstance (s,  unicode ): 
     #s=u"中文"  
     print  s.encode( 'gb2312' ) 
else : 
     #s="中文"  
     print  s.decode( 'utf-8' ).encode( 'gb2312' )
#!/usr/bin/env python
#coding=utf-8
s = "中文"
if  isinstance (s,  unicode ):
  #s=u"中文"
  print  s.encode( 'gb2312' )
else :
  #s="中文"
  print  s.decode( 'utf-8' ).encode( 'gb2312' )


看看下面一段代码:


#!/usr/bin/env python  
#coding=utf-8  
#python version:2.7.4 
#system:windows xp 
   
import  httplib2
def  getPageContent(url):
     '''''
     使用httplib2用编程的方式根据url获取网页内容
     将bytes形式的内容转换成utf-8的字符串
     '''
     #使用ie9的user-agent,如果不设置user-agent将会得到403禁止访问 
     headers = { 'user-agent' : 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)' ,
             'cache-control' : 'no-cache' }
     if  url:
          response,content  =  httplib2.Http().request(url,headers = headers)
            
          if  response.status  = =  200  :
             return  content



import  sys  
reload (sys)  
sys.setdefaultencoding( 'utf-8' )    #修改默认编码方式,默认为ascci 
print  sys.getdefaultencoding()
   
content  =  getPageContent( "http://www.oschina.net/" )
print  content.decode( 'utf-8' ).encode( 'gb2312' )
#!/usr/bin/env python
#coding=utf-8
#python version:2.7.4
#system:windows xp
import  httplib2
def  getPageContent(url):
     '''
     使用httplib2用编程的方式根据url获取网页内容
     将bytes形式的内容转换成utf-8的字符串
     '''
     #使用ie9的user-agent,如果不设置user-agent将会得到403禁止访问
     headers = { 'user-agent' : 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)' ,
             'cache-control' : 'no-cache' }
     if  url:
          response,content  =  httplib2.Http().request(url,headers = headers)
          
          if  response.status  = =  200  :
             return  content



6
import  sys
reload (sys)
sys.setdefaultencoding( 'utf-8' )    #修改默认编码方式,默认为ascci
print  sys.getdefaultencoding()
content  =  getPageContent( "http://www.oschina.net/" )
print  content.decode( 'utf-8' ).encode( 'gb2312' )

上面的代码的意思:向www.oschina.net网站请求他的主页,(如果直接是utf-8编码,不能输出中文)想将编码方式为utf-8转向gd2312,出现问题三


当我把它将print content.decode('utf-8').encode('gb2312')改成  print content.decode('utf-8').encode('gb2312', ‘ignore’)时,OK了,可以显示中文了,但不敢确定是否为全部,貌似只有部分吧,有些不能用gb2312编码


然而,当我把网站换成 www.soso.com时,不用转为gb2312,用utf-8即可正常显示中文


总结一下:


 向文件直接输出ss会抛出同样的异常。在处理unicode中文字符串的时候,必须首先对它调用encode函数,转换成其它编码输出。这一点对各个环境都一样。在Python中,“str”对象就是一个字节数组,至于里面的内容是不是一个合法的字符串,以及这个字符串采用什么编码(gbk, utf-8, unicode)都不重要。这些内容需要用户自己记录和判断。这些的限制也同样适用于“unicode”对象。要记住“unicode”对象中的内容可绝对不一定就是合法的unicode字符串,我们很快就会看到这种情况。在windows的控制台上,支持gbk编码的str对象和unicode编码的unicode对象。


标签:编码,中文,utf,python,gb2312,乱码,print,unicode,encode
From: https://blog.51cto.com/u_6186189/6458381

相关文章

  • Python中http请求方法库汇总
    最近在使用python做接口测试,发现python中http请求方法有许多种,今天抽点时间把相关内容整理,分享给大家,具体内容如下所示:一、python自带库----urllib2python自带库urllib2使用的比较多,简单使用如下:importurllib2response=urllib2.urlopen('http://localhost:8080/jenkins/api/jso......
  • Python爬虫
    目录PythonSpider第一章爬虫入门1.1爬虫概述1.1.1爬虫原理1.1.2爬虫分类1.1.3爬虫应用1.2爬虫流程1.2.1爬取网页1.2.2解析网页1.2.3存储数据1.3爬虫协议1.3.1Robots协议1.3.2robots.txt文件简介1.3.3robots.txt文件详解1.3.4爬虫准则1.4爬虫环境1.4.1原生Python+......
  • 实验6 turtle绘图与python库应用编程体验
    task1_1代码:fromturtleimport*defmove(x,y):'''画笔移动到坐标(x,y)处'''penup()goto(x,y)pendown()defdraw(n,size=100):'''绘制边长为size的正n变形'''foriinrange(n):......
  • Python中的logging模块
    官方文档基本用法下面的代码展示了logging最基本的用法。#-*-coding:utf-8-*-importloggingimportsys#获取logger实例,如果参数为空则返回rootloggerlogger=logging.getLogger("AppName")#指定logger输出格式formatter=logging.Formatter('%(ascti......
  • Centos 7.4+ 通过anaconda 安装Python3.10
    做记录,在centos里安装3.10版本时,老是报错ssl。或者一些其他问题,做个记录吧。大概用了2天才弄好,主业不是运维所以不太了解在https://www.anaconda.com/官网下载安装,此处自己根据系统、根据版本,自己安装下载地址:https://www.anaconda.com/download#downloads安装好后condai......
  • 实验6 turtle绘图与python库应用编程体验
    实验任务1task1_1.py程序源码:1fromturtleimport*23defmove(x,y):#画笔移动到坐标(x,y)处4penup()5goto(x,y)6pendown()78defdraw(n,size=100):#绘制边长为size的正n变形9foriinrange(n):10forward(size)11......
  • python: Decorators
      #装饰器defprintpy(func):definner_func():func()print("hellopython!GeovinDu")returninner_func#@装饰器@printpydefprinthello():print("helloworld!")#调用printhello()'''De......
  • Python modbus_tk 库源码分析
    modbus_tk源代码分析前言modbus_tcp协议是工业项目中常见的一种基于TCP/IP协议的设备数据交互协议。作为TCP/IP协议的上层协议,modbus_tcp协议涉及到两个概念:client和server。但更标准的叫法应该是master和slave。Slave:TCP/IP协议中的server方Master:TCP/IP协......
  • 实验六 turtle绘图与python库应用编程体验
    1fromturtleimport*234defmove(x,y):5penup()6goto(x,y)7pendown()8910defdraw(n,size=100):11foriinrange(n):12fd(size)13left(360/n)141516defmain():17pensize(2)18pen......
  • python: generator
    a=10defaddgoled():globalaa+=1dd=[{'name':'zhang','age':10},{'name':'tu','age':13}]d={'name':'zhang','age':10}defadddict():globald#......