Cannot print character by character in Chinese string in Python

The following characters are contained in the test.txt file:

地藏菩萨本愿经卷上
忉利天宫神通品第一

I have this simple program:

f = open("test.txt")
text = f.read()
f.close()

print text

for c in text:
    print c,

print "\n------------"

for i in range(len(text)):
    print text[i],

Here is the result:

地藏菩萨本愿经卷上
忉利天宫神通品第一
------------ 
å œ ° è — マ è マ © è ミ ¨ æ œ ¬ æ „ ¿ ç » マ å ヘ · ä ¸ Š 
å ¿ ‰ å ˆ © å ¤ © å ® « ç ¥ ž é € š å " チ ç ¬ ¬ ä ¸ € 


å œ ° è — マ è マ © è ミ ¨ æ œ ¬ æ „ ¿ ç » マ å ヘ · ä ¸ Š 
å ¿ ‰ å ˆ © å ¤ © å ® « ç ¥ ž é € š å " チ ç ¬ ¬ ä ¸ €

"text" prints OK if I use "Print Text". But both methods trying to print character by character failed.

What's happening?

+3
source share
1 answer

First, you must first decode the data read from the file into utf-8:

>>> with open('abc1') as f:
        text = f.read().decode('utf-8')
...     
>>> print text                              
地藏菩萨本愿经卷上 忉利天宫神通品第一
>>> for x in text:
    print x,
...     
地 藏 菩 萨 本 愿 经 卷 上   忉 利 天 宫 神 通 品 第 一

Or use io.opento open the file with the required encoding:

>>> import io
>>> with io.open('abc1', encoding='utf-8') as f:
    text = f.read()
>>> for x in text:                              
    print x,
...     
地 藏 菩 萨 本 愿 经 卷 上   忉 利 天 宫 神 通 品 第 一
+4
source

All Articles