Python中使用中文

python的中文问题一直是困扰新手的头疼问题,这篇文章将给你详细地讲解一下这方面的知识。当然,几乎可以确定的是,在将来的版本中,python会彻底解决此问题,不用我们这么麻烦了。

先来看看python的版本:
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'

(一)
用记事本创建一个文件ChineseTest.py,默认ANSI:
s = "中文"
print s

测试一下瞧瞧:
E:/Project/Python/Test>python ChineseTest.py
  File "ChineseTest.py", line 1
SyntaxError: Non-ASCII character '/xd6' in file ChineseTest.py on line 1, but no encoding declared; see http://www.pytho
n.org/peps/pep-0263.html for details

偷偷地把文件编码改成UTF-8:
E:/Project/Python/Test>python ChineseTest.py
  File "ChineseTest.py", line 1
SyntaxError: Non-ASCII character '/xe4' in file ChineseTest.py on line 1, but no encoding declared; see http://www.pytho
n.org/peps/pep-0263.html for details

无济于事。。。
既然它提供了网址,那就看看吧。简单地浏览一下,终于知道如果文件里有非ASCII字符,需要在第一行或第二行指定编码声明。把ChineseTest.py文件的编码重新改为ANSI,并加上编码声明:
# coding=gbk
s = "中文"
print s

再试一下:
E:/Project/Python/Test>python ChineseTest.py
中文

正常咯:)
(二)
看一看它的长度:
# coding=gbk
s = "中文"
print len(s)
结果:4。
s这里是str类型,所以计算的时候一个中文相当于两个英文字符,因此长度为4。
我们这样写:
# coding=gbk
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略参数将用python默认的ASCII来解码
s3 = s.decode("gbk") #把str转换成unicode是decode,unicode函数作用与之相同
print len(s1)
print len(s2)
print len(s3)
结果:
2
2
2
(三)
接着来看看文件的处理:
建立一个文件test.txt,文件格式用ANSI,内容为:
abc中文
用python来读取
# coding=gbk
print open("Test.txt").read()
结果:abc中文
把文件格式改成UTF-8:
结果:abc涓枃
显然,这里需要解码:
# coding=gbk
import codecs
print open("Test.txt").read().decode("utf-8")
结果:abc中文
上面的test.txt我是用Editplus来编辑的,但当我用Windows自带的记事本编辑并存成UTF-8格式时,
运行时报错:
Traceback (most recent call last):
  File "ChineseTest.py", line 3, in <module>
    print open("Test.txt").read().decode("utf-8")
UnicodeEncodeError: 'gbk' codec can't encode character u'/ufeff' in position 0: illegal multibyte sequence

原来,某些软件,如notepad,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM)。
因此我们在读取时需要自己去掉这些字符,python中的codecs module定义了这个常量:
# coding=gbk
import codecs
data = open("Test.txt").read()
if data[:3] == codecs.BOM_UTF8:
 data = data[3:]
print data.decode("utf-8")
结果:abc中文

(四)一点遗留问题
在第二部分中,我们用unicode函数和decode方法把str转换成unicode。为什么这两个函数的参数用"gbk"呢?
第一反应是我们的编码声明里用了gbk(# coding=gbk),但真是这样?
修改一下源文件:
# coding=utf-8
s = "中文"
print unicode(s, "utf-8")
运行,报错:
Traceback (most recent call last):
  File "ChineseTest.py", line 3, in <module>
    s = unicode(s, "utf-8")
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data
显然,如果前面正常是因为两边都使用了gbk,那么这里我保持了两边utf-8一致,也应该正常,不至于报错。
更进一步的例子,如果我们这里转换仍然用gbk:
# coding=utf-8
s = "中文"
print unicode(s, "gbk")
结果:中文
翻阅了一篇英文资料,它大致讲解了python中的print原理:
When Python executes a print statement, it simply passes the output to the operating system (using fwrite() or something like it), and some other program is responsible for actually displaying that output on the screen. For example, on Windows, it might be the Windows console subsystem that displays the result. Or if you're using Windows and running Python on a Unix box somewhere else, your Windows SSH client is actually responsible for displaying the data. If you are running Python in an xterm on Unix, then xterm and your X server handle the display.

To print data reliably, you must know the encoding that this display program expects.

简单地说,python中的print直接把字符串传递给操作系统,所以你需要把str解码成与操作系统一致的格式。Windows使用CP936(几乎与gbk相同),所以这里可以使用gbk。
最后测试:
# coding=utf-8
s = "中文"
print unicode(s, "cp936")
结果:中文
<script><!-- d(["mb","/u003cspan class/u003dsg/u003e/u003cbr/u003e-- /u003cbr/u003e/u003ca href/u003d/"http://www.2maomao.com/blog/" target/u003d/"_blank/" onclick/u003d/"return top.js.openextlink(window,event,this)/"/u003ehttp://www.2maomao.com/blog/u003c/a/u003e/u003cbr/u003e/n--~--~---------~--~----~------/u003cwbr/u003e------~-------~--~----~/u003cbr/u003e/n来自: `python-cn`~/u003cwbr/u003echinesepythonusergroup 列表/n /u003cbr/u003e 发言: /u003ca href/u003d/"mailto:python-cn@googlegroups.com/" target/u003d/"_blank/" onclick/u003d/"return top.js.openextlink(window,event,this)/"/u003epython-cn@googlegroups.com/u003c/a/u003e | 退订: /u003ca href/u003d/"mailto:python-cn-unsubscribe@googlegroups.com/" target/u003d/"_blank/" onclick/u003d/"return top.js.openextlink(window,event,this)/"/u003epython-cn-unsubscribe@/u003cwbr/u003egooglegroups.com/u003c/a/u003e/n /u003cbr/u003e 详情: /u003ca href/u003d/"http://groups.google.com/group/python-cn/" target/u003d/"_blank/" onclick/u003d/"return top.js.openextlink(window,event,this)/"/u003ehttp://groups.google.com//u003cwbr/u003egroup/python-cn/u003c/a/u003e /u003cbr/u003e -~----------~----~----~----~--/u003cwbr/u003e----~----~------~--~---/u003cbr/u003e/n/u003cbr/u003e/n/u003c/span/u003e",0] ); //--></script> ========================

本文转自Python邮件列表:[CPyUG:47963] python unicode 和 中文 (zz,不知道原作者了)

### PHP 和 Python 传参乱码解决方案 #### 一、PHP 中文传参乱码问题分析与解决 在 PHP 开发过程中,如果涉及到 URL 参数传递或者表单提交时,可能会因为编码设置不一致而导致中文乱码。以下是常见的原因及其对应的解决方案: 1. **URL 编码问题** 当通过 GET 方法传递参数时,未对中文字符进行编码可能导致接收端无法正确解析。可以通过 `urlencode()` 函数对参数进行编码后再拼接到 URL 上[^2]。 ```php $param = urlencode("你好"); header("Location: test.php?name=" . $param); ``` 2. **HTML 表单提交编码** 如果 HTML 页面的 `<form>` 标签中未指定 `accept-charset` 属性,默认可能使用 ISO-8859-1 编码,从而导致 POST 数据乱码。需确保表单编码为 UTF-8。 ```html <form action="submit.php" method="post" accept-charset="UTF-8"> <input type="text" name="username" /> <button type="submit">Submit</button> </form> ``` 3. **PHP 文件本身的编码** 确保 PHP 脚本文件保存为 UTF-8 编码(无 BOM),并显式设置输出头信息为 UTF-8。 ```php header('Content-Type: text/html; charset=UTF-8'); ``` 4. **数据库连接编码** 若涉及 MySQL 数据库操作,需确认数据库连接使用的字符集是否统一为 UTF-8。可通过以下 SQL 命令调整[^2]。 ```sql SET NAMES utf8; ``` --- #### 二、Python 中文传参乱码问题分析与解决 在 Python 应用程序中,无论是作为客户端还是服务端,都可能出现因编码配置不当而引发的中文乱码现象。以下是具体的解决办法: 1. **URL 参数编码** 使用 `urllib.parse.quote_plus()` 对字符串进行 URL 安全编码,避免直接将未经处理的中文字符嵌入 URL 地址中[^4]。 ```python import urllib.parse param = urllib.parse.quote_plus("你好") url = f"http://example.com/test?name={param}" print(url) ``` 2. **HTTP 请求响应体解码** 在利用 `requests` 发起 HTTP 请求时,注意区分 `response.text` 和 `response.content` 的用途。前者会自动尝试基于 Content-Type 头部字段推断编码方式;后者则返回原始字节流,可手动指定解码规则[^1]。 ```python import requests r = requests.get("http://example.com/api") content = r.content.decode("utf-8") # 手动指定解码方式 print(content) ``` 3. **MySQL 连接字符集设定** 配置 PyMySQL 或其他 MySQL 接口驱动器时,应明确指明所期望的数据交换字符集为 UTF-8[^3]。 ```python import pymysql connection = pymysql.connect( host='localhost', user='root', password='password', database='testdb', charset='utf8mb4' # 设置字符集 ) cursor = connection.cursor() sql = "INSERT INTO users (name) VALUES (%s)" cursor.execute(sql, ("你好",)) connection.commit() ``` --- ### 总结 无论是在 PHP 还是 Python 环境下,要彻底杜绝中文传参过程中的乱码情况发生,关键是保持整个链路各环节之间的编码一致性——即前端页面、传输协议以及后台存储均采用相同的 Unicode 子集标准(推荐 UTF-8)。此外还需针对特定场景选用恰当工具函数完成必要的转换工作。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值