Encoding Issues Encountered When Printing Chinese Characters in Python

Beginners often encounter various encoding issues when printing Chinese characters. Here is a summary to help address these problems in the future.1. Issues with running the code

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

The code above is simple, but it does not respond when clicked to run.Solution: Add the following line to the code: # -*- coding:utf-8 -*-

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

2. Runtime error

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:\\xe6xb5x8b\\xe8xafx95\\xe5x86x85xe9x83xa8xe5xbcx80xe5x85xb3xe6x95xb4xe7x90x86.xlsx'

Solution: Chinese characters need encoding. When the directory contains Chinese characters, prefix it with ‘u’ because Python uses Unicode encoding internally, as follows:

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

3. The code runs normally this time, but the printed result is not in Chinese

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

To resolve this, the list type cannot be directly decoded using x1.sheet_names().decode, so the following method is used:Use: print [x.decode(‘unicode_escape’) for x in x1.sheet_names()]The result throws an error: Incorrect encoding

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: <span style="color:#ff0000;"><strong>'ascii' </strong></span> 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)

Three solutions:1. Use print isinstance(x, unicode) to check if the string is Unicode encoded. If it is, use print x.encode(‘gb2312’); if not, use 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')
Running result:
================= RESTART: E:\github\python-essay\r_excel.py =================
True威胁检测相关
TrueDP变量相关
TrueVPN、认证相关

<span>2. Method 1 can only iterate through the list and print. For lists in Python, you can install uniout using pip install uniout</span>

# -*- coding:utf-8 -*-
import xlrd
import uniout
x1 = xlrd.open_workbook(u"E:\测试\内部开关整理.xlsx")
print x1.sheet_names()
Running result:
================= RESTART: E:\github\python-essay\r_excel.py =================
[u'威胁检测相关', u'DP变量相关', u'VPN、认证相关']

<span>3. You also need to remove 'u'. Combining methods 1 and 2, this time it finally works correctly.</span>

# -*- coding:utf-8 -*-
import xlrd
import uniout
x1 = xlrd.open_workbook(u"E:\测试\内部开关整理.xlsx")
print [x.encode("gb2312") for x in x1.sheet_names()]
Running result:
================= RESTART: E:\github\python-essay\r_excel.py =================
['威胁检测相关', 'DP变量相关', 'VPN、认证相关']

Leave a Comment