Python 編碼轉換與中文處理
Python 編碼轉換與中文處理
python 中的 unicode是讓人很困惑、比較難以理解的問題. utf-8是unicode的一種實現方式,unicode、gbk、gb2312是編碼字符集.
decode是將普通字串按照引數中的編碼格式進行解析,然後生成對應的unicode物件
寫python時遇到的中文編碼問題:
➜ /test sudo vim test.py #!/usr/bin/python #-*- coding:utf-8 -*- def weather(): import time import re import urllib2 import itchat #模擬瀏覽器 hearders = "User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36" url = "" ##要爬去天氣預報的網址 par = '()' ##正則匹配,匹配出網頁內要的內容 ##建立opener物件並設定為全域性物件 opener = urllib2.build_opener() opener.addheaders = [hearders] urllib2.install_opener(opener) ##獲取網頁 html = urllib2.urlopen(url).read().decode("utf-8") ##提取需要爬取的內容 data = re.search(par,html).group(2) print type(data) data.encode('gb2312') b = '天氣預報' print type(b) c = b + 'n' + data print c weather()
➜ /test sudo python test.pyTraceback (most recent call last): File "test.py", line 30, in weather() File "test.py", line 28, in weather c = b + 'n' + data UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
解決方法:
➜ /test sudo vim test.py #!/usr/bin/python #-*- coding:utf-8 -*- import sys reload(sys) # Python2.5 初始化後會刪除 sys.setdefaultencoding 這個方法,我們需要重新載入 sys.setdefaultencoding('utf-8') def weather(): import time import re import urllib2 import itchat #模擬瀏覽器 hearders = "User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36" url = "" ##要爬去天氣預報的網址 par = '()' ##正則匹配,匹配出網頁內要的內容 ##建立opener物件並設定為全域性物件 opener = urllib2.build_opener() opener.addheaders = [hearders] urllib2.install_opener(opener) ##獲取網頁 html = urllib2.urlopen(url).read().decode("utf-8") ##提取需要爬取的內容 data = re.search(par,html).group(2) print type(data) data.encode('gb2312') b = '天氣預報' print type(b) c = b + 'n' + data print c weather()
測試後:
➜ /test sudo python test.py
天氣預報
汕頭市今天實況:20度 多雲,溼度:57%,東風:2級。白天:20度,多雲。 夜間:晴,13度,天氣偏涼了,墨跡天氣建議您穿上厚些的外套或是保暖的羊毛衫,年老體弱者可以選擇保暖的搖粒絨外套。
個人感覺網上說中文亂碼通用解決辦法都是錯誤的,因為型別不一樣解決方法也不一樣,所以最近剛好出現了這種問題,從網上找了很多辦法沒解決到,最後自己去檢視資料,才發現需要對症下藥。
這是一個抓取網頁程式碼的python指令碼
➜ /test sudo cat file.py #!/usr/bin/python #_*_ coding:UTF-8 _*_ import urllib,urllib2 import re url = '' #抓取的url par = '20180125.*">(.*?)' req = urllib2.Request(url) response = urllib2.urlopen(req).read() #response = unicode(response,'GBK').encode('UTF-8') print type(response) print response
遇到的問題:
使用中文抓取中文網頁時,print出來的中文會出現亂碼
➜ /test sudo python file.py special.wait({ itemspaceid : 99999, form:"bigView", adsrc : 200, order : 1, max_turn : 1, spec :{ onBeforeRender: function(){ }, onAfterRender: function(){ }, isCloseBtn:true//�Ƿ��йرհ�ť } });
解決方法:
檢視網頁原始碼發現charset=GBK的型別所以python中要進行型別轉換
➜ /test sudo cat file.py #!/usr/bin/python #_*_ coding:UTF-8 _*_ import urllib,urllib2 import re url = '' #抓取的url par = '20180125.*">(.*?)' req = urllib2.Request(url) response = urllib2.urlopen(req).read() response = unicode(response,'GBK').encode('UTF-8') print type(response) print response
➜ /test sudo python file.py special.wait({ itemspaceid : 99999, form:"bigView", adsrc : 200, order : 1, max_turn : 1, spec :{ onBeforeRender: function(){ }, onAfterRender: function(){ }, isCloseBtn:true//是否有關閉按鈕 } });
現在已經把中文亂碼解決了
import json
#列印字典
dict = {'name': '張三'}
print json.dumps(dict, encoding="UTF-8", ensure_ascii=False)>>>{'name': '張三'}
#列印列表
list = [{'name': '張三'}]
print json.dumps(list, encoding="UTF-8", ensure_ascii=False)>>>[{'name': '張三'}]
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2331/viewspace-2802392/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- python處理抓取中文編碼和判斷編碼Python
- python unicode轉中文及轉換預設編碼PythonUnicode
- PHP中文字元gbk編碼與UTF-8編碼的轉換PHP字元
- C++ url中文編碼處理 編碼轉為UTF8 CChineseCode下載C++
- ptyon 特殊處理 url 編碼與解碼,字元編碼轉化 unicode字元Unicode
- Python編解碼問題與文字檔案處理Python
- 字元編碼與檔案處理字元
- python中的urlencode和urldecode 【中文和url編碼轉換】Python
- Python 編碼處理之 str與Unicode的區別與使用PythonUnicode
- Python 字元編碼轉換祕訣Python字元
- Python 中文編碼Python
- Java SimpleDateFormat處理日期與字串的轉換JavaORM字串
- python處理瀏覽器URL編碼Python瀏覽器
- 編碼轉換
- 【視訊處理】YUV與RGB格式轉換
- Linux 字元編碼 檢視與轉換Linux字元
- 字元編碼轉換字元
- URL編碼轉換
- jQuery AJAX中文亂碼處理jQuery
- UTF-8編碼與GBK編碼之間的轉換
- codecs 編碼處理
- WindowsPhone的中文GB2312、GBK編碼與Unicode相互轉換WindowsUnicode
- python 中文編碼問題Python
- 處理JSP中的中文 (轉)JS
- JavaMail中文附件的處理方法 (轉)JavaAI
- java的中文亂碼轉換Java
- python編寫圖片主色轉換指令碼Python指令碼
- 位元組編碼轉換
- java字元編碼轉換Java字元
- java處理中文亂碼問題Java
- 【Java】基本資料、包裝類間轉換與處理Java
- [Java] 基本資料、包裝類間轉換與處理Java
- 文字編碼轉換工具iconv 附批量轉換檔案編碼命令
- 將DOS批處理檔案轉換為Shell指令碼指令碼
- 中文被 json_encode 編碼成 unicode 之後如何轉換回中文JSONUnicode
- Python的中文編碼問題Python
- Python數字轉換中文大寫Python
- python與編碼Python