Python中文亂碼問題

2022-01-30 19:23:41 字數 678 閱讀 6855

字串在python內部的表示是unicode編碼,因此,在做編碼轉換時,通常需要以unicode作為中間編碼,即先將其他編碼的字串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。

decode的作用是將其他編碼的字串轉換成unicode編碼,如str1.decode('gb2312'),表示將gb2312編碼的字串str1轉換成unicode編碼。

encode的作用是將unicode編碼轉換成其他編碼的字串,如str2.encode('gb2312'),表示將unicode編碼的字串str2轉換成gb2312編碼。

因此,轉碼的時候一定要先搞明白,字串str是什麼編碼,然後decode成unicode,然後再encode成其他編碼。

獲得系統的預設編碼?

#!/usr/bin/env python

#coding=utf-8

import sys

print sys.getdefaultencoding()

在用python抓取網頁時,由於不同**所採用的編碼不同,使用decode時先知道該網頁所採用的編碼,也可以用python來獲得

req=urllib2.request("")

fd=urllib2.urlopen(req)

print fd.headers['content-type']

python 中文亂碼問題

python 中文亂碼問題 python 預設編碼和系統編碼有關 linux 下用locale命令可以檢視 加入以下編碼可以將預設編碼設定為utf8 import sys reload sys sys.setdefaultencoding utf 8 處理中文時候,可以用urllib.quote將u...

Python中文亂碼問題 MySQL

最近在學習使用python操作mysql資料庫,遇到了中文亂碼問題。一 mysql資料庫 庫字符集引數 character set utf8 表字符集引數 charset utf8 列字符集引數 character set utf8 二 python檔案 檔案編碼utf 8 檔案頭新增 encodi...

Python解決中文亂碼問題

如果你從hdfs上匯出csv檔案,可能存在中文亂碼問題。用多個編輯器 工具都不能解決,可以用如下python 輕鬆搞定。匯出語句 hive e select from xx.table data tmp abc.csv python importpandasaspd dat pd.read tabl...