亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

Python 轉(zhuǎn)換文本編碼實(shí)現(xiàn)解析

系統(tǒng) 1780 0

最近在做周報(bào)的時(shí)候,需要把csv文本中的數(shù)據(jù)提取出來(lái)制作表格后生產(chǎn)圖表。

在獲取csv文本內(nèi)容的時(shí)候,基本上都是用with open(filename, encoding ='UTF-8') as f:來(lái)打開(kāi)csv文本,但是實(shí)際使用過(guò)程中發(fā)現(xiàn)有些csv文本并不是utf-8格式,從而導(dǎo)致程序在run的過(guò)程中報(bào)錯(cuò),每次都需要手動(dòng)去把該文本文件的編碼格式修改成utf-8,再次來(lái)run該程序,所以想說(shuō):直接在程序中判斷并修改文本編碼。

基本思路:先查找該文本是否是utf-8的編碼,如果不是則修改為utf-8編碼的文本,然后再處理。

python有chardet庫(kù)可以查看到文本的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']
          

不過(guò)這個(gè)在從處理小文件的時(shí)候性能還行,如果文本稍微過(guò)大就很慢了,目前我本地的csv文件是近200k,就能明顯感覺(jué)到速度過(guò)慢了,效率低下。不過(guò)chardet庫(kù)中提供UniversalDetector對(duì)象來(lái)處理:創(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è)器之前沒(méi)有達(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í)候遇到問(wèn)題:UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 178365: character maps to

            
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)  #-->此處有問(wèn)題
  file_encode = file_decode.encode(des_encode)
  write_file(file_encode, file)
          

這是由于byte字符組沒(méi)解碼好,要加另外一個(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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 性做久久| 人人爱天天做夜夜爽毛片 | 国产日产精品 | 国产福利免费观看 | 欧美一级视频免费 | 九九热在线精品 | 四虎国产永久在线观看 | 国产成人精品视频 | 天天操狠狠操夜夜操 | 91福利国产在线观看一区二区 | 国产一区亚洲一区 | 九九精品在线观看 | 五月婷视频 | 性欧美另类老妇高清 | 成人国产欧美精品一区二区 | 九九精品久久 | 欧美性猛交ⅹxxx乱大交按摩 | 夜夜躁日日躁狠狠久久 | 日韩 欧美 亚洲 中文字幕 | 天天伊人 | avav国产| 欧美激情伦妇在线观看 | 免费深夜福利 | 久久精品免费看 | 亚洲码欧美码一区二区三区 | 91九色蝌蚪 | 狠狠色噜噜| 99久久免费国产精品特黄 | xxx中国毛茸茸 | 欧美一欧美一级毛片 | 五月天婷亚洲 | 精品91自产拍在线观看99re | 亚洲欧美第一 | 日本一区二区三区在线 观看网站 | 午夜精品久久久久久久90蜜桃 | 男人资源站 | 一级毛片免费观看不收费 | 四虎精品成人免费影视 | 欧美三区在线 | 韩国亚洲伊人久久综合影院 | 国产亚洲精品成人a在线 |