python print中文时遇到的编码问题

新手在print中文是遇到了很多编码的问题,总结一下,以后遇到了继续补充

1、无法运行的问题

import xlrd
x1 = xlrd.open_workbook("E:\\测试\\内部开关整理.xlsx")
print x1.sheet_names()

如上代码,简单写了三行,但怎么点击运行都没反应

解决方法:代码添加: # -*- coding:utf-8 -*- 

# -*- coding:utf-8 -*-
import xlrd
x1 = xlrd.open_workbook("E:\\测试\\内部开关整理.xlsx")
print x1.sheet_names()

2、运行报错

Traceback (most recent call last):
  File "E:\github\python-essay\r_excel.py", line 4, in <module>
    x1 = xlrd.open_workbook("E:\\测试\\内部开关整理.xlsx")
  File "D:\ruanjian1\python\lib\site-packages\xlrd\__init__.py", line 116, in open_workbook
    with open(filename, "rb") as f:
IOError: [Errno 2] No such file or directory: 'E:\\\xe6\xb5\x8b\xe8\xaf\x95\\\xe5\x86\x85\xe9\x83\xa8\xe5\xbc\x80\xe5\x85\xb3\xe6\x95\xb4\xe7\x90\x86.xlsx'

 解决方法:中文需要编码,目录带中文时前面加u,因为python内部是Unicode编码的,即:

# -*- coding:utf-8 -*-
import xlrd
x1 = xlrd.open_workbook(u"E:\\测试\\内部开关整理.xlsx")
print x1.sheet_names()

3、这次正常运行,但结果打印出来的不是中文

================= RESTART: E:\github\python-essay\r_excel.py =================
[u'\u5a01\u80c1\u68c0\u6d4b\u76f8\u5173', u'DP\u53d8\u91cf\u76f8\u5173', u'VPN\u3001\u8ba4\u8bc1\u76f8\u5173']

继续想解决方法,list类型不能这样直接 x1.sheet_names().decode,所以使用下面的形式

使用了  print [x.decode('unicode_escape') for x in x1.sheet_names()]

结果报错: 编码不对

Traceback (most recent call last):
  File "E:\github\python-essay\r_excel.py", line 6, in <module>
    print [x.decode('unicode_escape') for x in x1.sheet_names()]
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

三种解决方法:

1、 print isinstance(x, unicode)   查看字符串是否为Unicode编码,是使用print x.encode('gb2312'),不是则使用print x.encode('utf-8')

# -*- coding:utf-8 -*-

import xlrd

x1 = xlrd.open_workbook(u"E:\\测试\\内部开关整理.xlsx")
for x in x1.sheet_names():
    print isinstance(x, unicode)
    print x.encode('gb2312')
运行结果:
================= RESTART: E:\github\python-essay\r_excel.py =================
True
威胁检测相关
True
DP变量相关
True
VPN、认证相关

2、方法1只能遍历列表再打印,对于python中的list ,可以安装uniout,pip install uniout

# -*- coding:utf-8 -*-
import xlrd
import uniout
x1 = xlrd.open_workbook(u"E:\\测试\\内部开关整理.xlsx")
print x1.sheet_names()

运行结果:
================= RESTART: E:\github\python-essay\r_excel.py =================
[u'威胁检测相关', u'DP变量相关', u'VPN、认证相关']

3、还需要去掉u,就结和1/2,这次终于正常了

# -*- coding:utf-8 -*-

import xlrd
import uniout

x1 = xlrd.open_workbook(u"E:\\测试\\内部开关整理.xlsx")
print [x.encode("gb2312") for x in x1.sheet_names()]
运行结果:
================= RESTART: E:\github\python-essay\r_excel.py =================
['威胁检测相关', 'DP变量相关', 'VPN、认证相关']

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值