Python 轉(zhuǎn)換文本編碼實(shí)現(xiàn)解析
最近在做周報(bào)的時(shí)候,需要把csv文本中的數(shù)據(jù)提取出來制作表格后生產(chǎn)圖表。
在獲取csv文本內(nèi)容的時(shí)候,基本上都是用with open(filename, encoding ='UTF-8') as f:來打開csv文本,但是實(shí)際使用過程中發(fā)現(xiàn)有些csv文本并不是utf-8格式,從而導(dǎo)致程序在run的過程中報(bào)錯(cuò),每次都需要手動(dòng)去把該文本文件的編碼格式修改成utf-8,再次來run該程序,所以想說:直接在程序中判斷并修改文本編碼。
基本思路:先查找該文本是否是utf-8的編碼,如果不是則修改為utf-8編碼的文本,然后再處理。
python有chardet庫可以查看到文本的encoding信息:
detect函數(shù)只需要一個(gè) 非unicode字符串參數(shù),返回一個(gè)字典(例如:{'encoding': 'utf-8', 'confidence': 0.99})。該字典包括判斷到的編碼格式及判斷的置信度。
import chardet
def get_encode_info(file):
with open(file, 'rb') as f:
return chardet.detect(f.read())['encoding']
不過這個(gè)在從處理小文件的時(shí)候性能還行,如果文本稍微過大就很慢了,目前我本地的csv文件是近200k,就能明顯感覺到速度過慢了,效率低下。不過chardet庫中提供UniversalDetector對(duì)象來處理:創(chuàng)建UniversalDetector對(duì)象,然后對(duì)每個(gè)文本塊重復(fù)調(diào)用其feed方法。如果檢測(cè)器達(dá)到了最小置信閾值,它就會(huì)將detector.done設(shè)置為True。
一旦您用完了源文本,請(qǐng)調(diào)用detector.close(),這將完成一些最后的計(jì)算,以防檢測(cè)器之前沒有達(dá)到其最小置信閾值。結(jié)果將是一個(gè)字典,其中包含自動(dòng)檢測(cè)的字符編碼和置信度(與charde.test函數(shù)返回的相同)。
from chardet.universaldetector import UniversalDetector
def get_encode_info(file):
with open(file, 'rb') as f:
detector = UniversalDetector()
for line in f.readlines():
detector.feed(line)
if detector.done:
break
detector.close()
return detector.result['encoding']
在做編碼轉(zhuǎn)換的時(shí)候遇到問題:UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 178365: character maps to <undefined>
def read_file(file):
with open(file, 'rb') as f:
return f.read()
def write_file(content, file):
with open(file, 'wb') as f:
f.write(content)
def convert_encode2utf8(file, original_encode, des_encode):
file_content = read_file(file)
file_decode = file_content.decode(original_encode) #-->此處有問題
file_encode = file_decode.encode(des_encode)
write_file(file_encode, file)
這是由于byte字符組沒解碼好,要加另外一個(gè)參數(shù)errors。官方文檔中寫道:
bytearray.decode(encoding=”utf-8”, errors=”strict”)
Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
意思就是字符數(shù)組解碼成一個(gè)utf-8的字符串,可能被設(shè)置成不同的處理方案,默認(rèn)是‘嚴(yán)格'的,有可能拋出UnicodeError,可以改成‘ignore','replace'就能解決。
所以將此行代碼file_decode = file_content.decode(original_encode)修改成file_decode = file_content.decode(original_encode,'ignore')即可。
完整代碼:
from chardet.universaldetector import UniversalDetector
def get_encode_info(file):
with open(file, 'rb') as f:
detector = UniversalDetector()
for line in f.readlines():
detector.feed(line)
if detector.done:
break
detector.close()
return detector.result['encoding']
def read_file(file):
with open(file, 'rb') as f:
return f.read()
def write_file(content, file):
with open(file, 'wb') as f:
f.write(content)
def convert_encode2utf8(file, original_encode, des_encode):
file_content = read_file(file)
file_decode = file_content.decode(original_encode,'ignore')
file_encode = file_decode.encode(des_encode)
write_file(file_encode, file)
if __name__ == "__main__":
filename = r'C:\Users\danvy\Desktop\Automation\testdata\test.csv'
file_content = read_file(filename)
encode_info = get_encode_info(filename)
if encode_info != 'utf-8':
convert_encode2utf8(filename, encode_info, 'utf-8')
encode_info = get_encode_info(filename)
print(encode_info)
參考:https://chardet.readthedocs.io/en/latest/usage.html
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python使用pandas實(shí)現(xiàn)數(shù)據(jù)分割實(shí)例代碼
這篇文章主要介紹了python使用pandas實(shí)現(xiàn)數(shù)據(jù)分割實(shí)例代碼,介紹了使用pandas實(shí)現(xiàn)對(duì)dataframe格式的數(shù)據(jù)分割成時(shí)間跨度相等的數(shù)據(jù)塊,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
python?open讀取文件內(nèi)容時(shí)的mode模式解析
這篇文章主要介紹了python?open讀取文件內(nèi)容時(shí)的mode模式解析,Python可以使用open函數(shù)來實(shí)現(xiàn)文件的打開,關(guān)閉,讀寫操作,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
使用python求解迷宮問題的三種實(shí)現(xiàn)方法
關(guān)于迷宮問題,常見會(huì)問能不能到達(dá)某點(diǎn),以及打印到達(dá)的最短路徑,下面這篇文章主要給大家介紹了關(guān)于如何使用python求解迷宮問題的三種實(shí)現(xiàn)方法,需要的朋友可以參考下2022-03-03
詳解Python?Selenium如何獲取鼠標(biāo)指向的元素
這篇文章主要介紹了如何通過Selenium獲取當(dāng)前鼠標(biāo)指向的元素,本文方法的核心,是借助JavaScript的事件(event)來獲取鼠標(biāo)所在的元素,感興趣的可以試一試2022-03-03
用python按照?qǐng)D像灰度值統(tǒng)計(jì)并篩選圖片的操作(PIL,shutil,os)
這篇文章主要介紹了用python按照?qǐng)D像灰度值統(tǒng)計(jì)并篩選圖片的操作(PIL,shutil,os),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python如何設(shè)置utf-8為默認(rèn)編碼的問題
這篇文章主要介紹了Python如何設(shè)置utf-8為默認(rèn)編碼的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
Django Admin 管理工具的實(shí)現(xiàn)
這篇文章主要介紹了Django Admin 管理工具的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
使用Python實(shí)現(xiàn)圖像有效壓縮的方法
在數(shù)字時(shí)代,圖像作為信息傳遞的重要媒介,在網(wǎng)頁設(shè)計(jì)、移動(dòng)應(yīng)用和多媒體制作中扮演著不可或缺的角色,本文將詳細(xì)介紹如何使用Python,一個(gè)功能強(qiáng)大且易于學(xué)習(xí)的編程語言,來實(shí)現(xiàn)圖像的有效壓縮,感興趣的朋友可以參考下2024-03-03

