python支持中文

环境:python 2.7.*

做法:

在.py文件中,要加

# -*- coding:utf-9 -*-

如果要支持中文,必须在中文前面加u,如u‘我是pythoner’


解释:

>>> test1 = "我是pythoner"

>>> test2 = u"我是pythoner"

>>> test1
'\xe6\x88\x91\xe6\x98\xafpythoner'
>>> test2
u'\u6211\u662fpythoner'


>>> test11 = test1.encode('gb2312')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
>>> test12 = test1.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
>>> test13 = test1.decode('utf-8')
>>> test13
u'\u6211\u662fpythoner'
>>> test14 = test1.decode('gb2312')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 0-1: illegal multibyte sequence

>>> test15 = test1.decode('utf-8').encode('utf-8')
>>> test15
'\xe6\x88\x91\xe6\x98\xafpythoner'
>>> test16 = test1.decode('utf-8').encode('gb2312')
>>> test16
'\xce\xd2\xca\xc7pythoner'

>>> test21 = test2.encode('gb2312')
>>> test21
'\xce\xd2\xca\xc7pythoner'
>>> test22 = test21.decode('gb2312')
>>> test22
u'\u6211\u662fpythoner'
>>> test23 = test2.encode('gb18030')
>>> test23
'\xce\xd2\xca\xc7pythoner'
>>> test24 = test23.decode('gb2312')
>>> test24
u'\u6211\u662fpythoner'

>>> test25 = test23.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)


结论:

        本来是gb2312码,只能解码为utf-8 ,后编码为gb18030码

        本来是utf-8码,编码为其他码,解码的时候,也要为相应的码。

### 设置 Python 中文支持 为了使 Python 支持中文,主要涉及编码配置以及环境变量设置两方面。 #### 编码声明 当编写源代码文件时,在文件顶部加入如下语句来指定文件使用的字符集为 UTF-8,这有助于处理包含汉字在内的多种语言文字[^1]: ```python # -*- coding: utf-8 -*- ``` #### 控制台输出 对于命令行界面下的程序来说,如果遇到乱码问题,则需确认操作系统的区域和语言选项已调整至兼容状态。另外一种方法是在脚本开头处添加以下几行代码以改变标准输出流的默认编码方式: ```python import sys sys.stdout.reconfigure(encoding='utf-8') #适用于Python 3.7+ ``` 或者使用 `io` 模块重定向 stdout: ```python from io import TextIOWrapper import sys sys.stdout = TextIOWrapper(sys.stdout.buffer,encoding="utf-8") ``` #### 文件读写 在打开含有非 ASCII 字符的数据文件之前,记得指明所期望采用的具体编码格式,比如读取文本文件可以这样做: ```python with open('example.txt', 'r', encoding='utf-8') as f: content = f.read() print(content) ``` 同样地,在保存带有特殊字符的内容到磁盘上时也应如此操作。 #### 环境变量设定 有时还需要修改操作系统级别的环境参数,特别是针对 Windows 用户而言,可以通过控制面板中的“地区”设置更改系统 locale 或者直接通过命令提示符执行下面这条指令临时生效: ```bash chcp 65001 ``` 以上措施能够有效解决大部分情况下关于 Python 对于中文支持不足的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值