Python,如何打印日文、韩文、中文字符串 [英] Python, how to print Japanese, Korean, Chinese strings

查看:124
本文介绍了Python,如何打印日文、韩文、中文字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,对于日文、中文和韩文,Python无法打印正确的字符串,例如hello在日文、韩文和中文中分别是:

In Python, for Japanese, Chinese, and Korean,Python can not print the correct strings, for example hello in Japanese, Korean and Chinese are:

こんにちは
안녕하세요
你好

并打印这些字符串:

In [1]: f = open('test.txt')

In [2]: for _line in f.readlines():
   ...:     print(_line)
   ...:     
こんにちは

안녕하세요

你好


In [3]: f = open('test.txt')

In [4]: print(f.readlines())
[ '\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf\n', '\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x84\xb8\xec\x9a\x94\n', '\xe4\xbd\xa0\xe5\xa5\xbd\n']

In [5]: a = '你好'

In [6]: a
Out[6]: '\xe4\xbd\xa0\xe5\xa5\xbd'

我的 Python 版本是 2.7.11,操作系统是 Ubuntu 14.04

My Python version is 2.7.11 and OS is Ubuntu 14.04

如何处理这些'\xe4\xbd\xa0\xe5\xa5\xbd\n' 字符串.

How to handle these '\xe4\xbd\xa0\xe5\xa5\xbd\n' strings.

谢谢!

推荐答案

首先你需要把文字读成 unicode

First you need to read the text as unicode

import codecs
f = codecs.open('test.txt','r','utf-8')

第二

打印时应该像这样编码

unicodeText.encode('utf-8')

第三个

你应该确保你的控制台支持unicode显示

you should insure that your console support unicode display

使用

print sys.getdefaultencoding()

如果没有试试

reload(sys)
sys.setdefaultencoding('utf-8')

这篇关于Python,如何打印日文、韩文、中文字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆