UnicodeEncodeError: 'gbk' codec can't encode character '\xc4' 这类问题之解决

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/RobertChenGuangzhi/article/details/77971015

问题描述

在看书籍《Mark Lutz. Learning Python. 5ed. O’Reilly 2013》的106页的一个例子时,如下:

>>> print('sp\xc4m')

在我的win7电脑的cmd console中以交互式的方式运行,不仅得不到与书中相同的结果,反而得到以下错误:

UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xc4’

在网上搜索了半天,前前后后折腾了2个多小时,始终没有解决。按网上的各种解决方法,都不奏效。

实际上,上述问题我两年前即已碰到。当时,该书刚刚出版没多久,也是看该例子的时候,与书上的运行结果不一致,且出现报错。我把出现错误的原因归为中文操作系统的缘故,因为该书是2013年出版的英文原版书,书的作者在写该书前,必定用的是英文的操作系统。

解决方案

晚上回到休息的酒店,就登录了anaconda的最新下载页面,发现Anaconda已经更新到4.4.0版本了。自己在备课的过程中已经发现math库增加了两个常量,相比Python 3.4.4来说,分别为math.inf和math.nan。何不就装一个新版本的Anaconda试试。

特别注意,我原来使用的Anaconda版本及Python版本如下:

  • Anaconda 4.0.0
  • Python 3.4.4

我新安装的版本为:

  • Anaconda 4.4.0
  • Python 3.6.1
    我再次运行书中的例子如下:
    这里写图片描述
    发现与书中的运行结果完全一致,问题得以解决。

结论

由此可知,最新版本的Python 3.6.1完美地解决了以前版本中的处理unicode字符的bug问题,在直接支持Unicode字符处理方面的能力得到了增强。

展开阅读全文

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2026' in position

02-09

爬虫代码如下:rnimport requests,jsonrnimport pymysqlrn#1.请求一个单页的内容rndef get_one_page(url):rn headers='User-Agent':'Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/58.0'rn response=requests.get(url,headers=headers)rn return response.content.decode('utf-8')rn#解析、rndata = []rndef parse_one_page(html):rn dataJson=json.loads(html)rn print(html)rn # print(dataJson['data']);rn for n in dataJson['data']['data']:rn c=n['summary']rn yield crn#3.保存(将数据存入数据库)rndef write_to_mysql(content):rn conn=pymysql.connect(host='localhost',user='root',passwd='123456',db='neihan',charset='utf8')rn cur=conn.cursor()rn neirong=contentrn sql='insert into duanzi values(NULL,%s)'rn parm=(neirong,)rn try:rn cur.execute(sql,parm)rn conn.commit()rn except Exception:rn passrn cur.close()rn conn.close()rn#4.定义主函数rndef main(timestamp):rn # while type(timestamp)==int or type(timestamp)==float:rn for j in range(1):rn url='http://pclistinterface.mop.com/mdi/data.html?jsonpcallback=' \rn 'success_jsonpCallback&pgnum=1&colid=110035&pgsize=20&serialnum' \rn '=300000&startcol=10019&mirrorid=1518140521&platform=pc&uid=' \rn '15179020020634794&qid=null&login=null&_='+str(timestamp)rn print(url)rn html=get_one_page(url)rn # dataJson = json.loads(html)rn i=1rn for item in parse_one_page(html):rn #print(item)rn item=item.strip()rn if item:rn write_to_mysql(item.strip())rn i+=1rn #imestamp=dataJson['data']['max_time']rnmain(1518140521) 论坛

'ascii' codec can't encode characters in position 0-10: ordinal not in range

10-09

我写了下面的代码,首次运行后提示“'ascii' codec can't encode characters in position 0-10: ordinal not in range”,然后在网上搜了一下此问题,就在文件的顶部加入“reload(sys) sys.setdefaultencoding( "utf-8" )”,但是点击F5运行程序就什么也出不来了。rnrn# -*- coding: cp936 -*- rnimport arcpy, os,sysrnrn__name__='publishHelper' rn rn# 将指定目录下所有的.mxd文档发布为地图服务 rn# folder:包含mxd文档的文件夹路径 rn# serviceDir:服务目录URL,例如http://localhost/arcgis/rest/services rn# serviceFolder:服务所在文件夹,如果为空,则表示根目录 rndef PublishAll(folder,serviceDir,serviceFolder): rn print "检查文件夹路径……" rn if os.path.isdir(folder) == False: rn print "输入的文件夹路径无效!" rn return rn print "遍历文件夹……" rn files = os.listdir(folder) rn for f in files: rn if f.endswith(".mxd"): rn mxdPath = os.path.join(folder, f) rn print "publishing: " + f rn PublishMxd(mxdPath, serviceDir, serviceFolder) rn else: rn continue rn#将mxd文档发布为服务:1.将mxd转为msd;2.分析msd;3.发布msd rndef PublishMxd(mxdPath, serviceDir, serviceFolder): rn #检查mxd和msd文件是否存在 rn print "检查文件路径……" rn if os.path.exists(mxdPath) == False: rn print "指定路径的mxd文档不存在!" rn return rn rn # 打开mxd文档 rn try: rn print "正在打开mxd文档……" rn mxd = arcpy.mapping.MapDocument(mxdPath) rn except Exception, e: rn print "open mxd error: ", e rn return rn else: rn print "mxd文档打开成功……" rn rn # 获取默认的数据框 rn print "正在读取mxd文档默认数据框……" rn df = "" rn try: rn frames = arcpy.mapping.ListDataFrames(mxd, "图层") rn if len(frames) == 0: rn frames = arcpy.mapping.ListDataFrames(mxd, "Layers") rn df = frames[0] rn except Exception, e: rn print "读取mxd文档默认数据框失败:", e rn return rn rn # 构造msd文档名称 rn msdPath = mxdPath.replace(".mxd", ".msd") rn # 将mxd转为msd rn print "正在将mxd文档转换为msd文档……" rn arcpy.mapping.ConvertToMSD(mxd, msdPath, df, "NORMAL", "NORMAL") rn rn # 分析msd rn print "正在分析文档……" rn analysis = arcpy.mapping.AnalyzeForMSD(mxd) rn # 列出分析结果信息 rn for key in ('messages', 'warnings', 'errors'): rn print "----" + key.upper() + "---" rn vars = analysis[key] rn for ((message, code), layerlist) in vars.iteritems(): rn print " ", message, " (CODE %i)" % code rn print " applies to:", rn for layer in layerlist: rn print layer.name, rn print rn rn #获取服务器信息 rn serviceName = os.path.basename(msdPath).replace(".msd", "") rn serverName = serviceDir.split("/")[2] rn try: rn #发布msd rn print "正在发布服务……" rn arcpy.mapping.PublishMSDToServer (msdPath, serviceDir, serverName, serviceName, serviceFolder, ["WMS", "KML"]) rn except Exception, e: rn print "发布服务失败:", e rn else: rn print "服务发布成功!" rnrnPublishAll("E:\\englishFileTwo", "http://localhost:6080/arcgis/rest/services", "dlwy") 论坛

python django :Exception Value: 'ascii' codec can't encode characters in positi

09-06

如果在models.py 里这样定义: rnrnmodels.py: rninfopic = models.FileField(upload_to='./pic/%Y/%m/%d/%H/', blank=True, null=True) rnrnfomrs.py: rninfopic = forms.FileField(label=u'相关图片', required=False) rnrnrnvimews.py: rnif form.is_valid(): rnnewinfo = Gqinfo( rntitle = form.cleaned_data['title'], rncontent = form.cleaned_data['content'], rninfopic = form.cleaned_data['infopic'], rnuser = request.user, rn) rnnewinfo.save() rnrnrnrn如果上传的图片里路径或图片的名字是中文的。比如: 中国.jpg 中国123.jpb rnrn在发布信息的时候就会出错。提示: rnrnrnrnrnrnEnvironment: rnrnrnRequest Method: POST rnRequest URL: http://www.aaa.com/post rnrnException Type: UnicodeEncodeError at /post/ rnException Value: 'ascii' codec can't encode characters in position 55-56: ordinal not in range(128) rnrnrnrnrnrnUnicodeEncodeError at /post/ rn'ascii' codec can't encode characters in position 55-56: ordinal not in range(128)Request Method: POST rnRequest URL: http://www.gq.com/post/ rnDjango Version: 1.5.2 rnException Type: UnicodeEncodeError rnException Value: 'ascii' codec can't encode characters in position 55-56: ordinal not in range(128) rnException Location: /usr/lib/python2.6/genericpath.py in exists, line 18 rnPython Executable: /usr/bin/python rnPython Version: 2.6.6 rnPython Path: ['/usr/lib/python26.zip', rn'/usr/lib/python2.6', rn'/usr/lib/python2.6/plat-linux2', rn'/usr/lib/python2.6/lib-tk', rn'/usr/lib/python2.6/lib-old', rn'/usr/lib/python2.6/lib-dynload', rn'/usr/lib/python2.6/site-packages', rnrnrnrnrnrnrn难道是那图片的路径不能是中文的吗? 论坛

没有更多推荐了,返回首页