Python判斷檔案和字串編碼型別的例項

2022-10-04 20:36:15 字數 1262 閱讀 2619

python判斷檔案和字串編碼型別可以用chardet工具包,可以識別大多數的編碼型別。但是前幾天在讀取乙個windows記事本儲存的txt檔案時,gbk卻被識別成了koi8-r,無解。

然後就自己寫了個簡單的編碼識別方法,**如下:

coding.py

# 說明:utf相容iso8859-1和ascii,gb18030相容gbk,gbk相容gb2312,gb2312相容ascii

codes = ['utf-8', 'utf-16', 'gb18030', 'big5']

# utf-8 bom前hnzoxopwcr綴位元組

utf_8_bom = b'\xef\xbb\xbf'

# 獲取檔案編碼型別

def file_encoding(file_path):

"""獲取檔案編碼型別\n

:param file_path: 檔案路徑\n

:return: \n

"""with open(file_path, 'rb') as f:

r程式設計客棧eturn string_encoding(f.read())

# 獲取字元編碼型別

def string_encoding(b: bytes):

"""獲取字元編碼型別\n

:param b: 位元組資料\n

:return: \n

"""# 遍歷編碼型別

for code in codes:

try:

b.decode(encoding=code)

if 'utf-8' == code and b.startswith(utf_8_bom):

re程式設計客棧turn 'utf-8-sig'

return code

except exception:

continue

return '未知的字元編碼型別'

說明:file_encoding方法用於判斷檔案編碼型別,引數為檔案路徑;string_encodwww.cppcns.coming方法用於判斷字串編碼型別,引數為字串對應的位元組資料

使用示例:

import coding

file_name = input('請輸入待識別檔案路徑:\n')

encoding = coding.file_encoding(file_name)

print(encoding)

本文標題: python判斷檔案和字串編碼型別的例項

本文位址: /jiaoben/python/215319.html

python判斷字串

python判斷字串 s為字串 s.isalnum 所有字元都是數字或者字母 s.isalpha 所有字元都是字母 s.isdigit 所有字元都是數字 s.islower 所有字元都是小寫 s.isupper 所有字元都是大寫 s.istitle 所有單詞都是首字母大寫,像標題 s.isspace...

判斷字串 python判斷字串是否包含字母

第一種方法 使用正規表示式判斷字串是否包含字母 coding utf 8 import re def check str my re re.compile r a za z re.s res re.findall my re,str if len res print u 含有英文本元 else pr...

判斷字串 python判斷字串以什麼開始

python在處理文字的時候經常需要判斷以什麼字串開頭,可以取字串索引進行判斷,也可以直接使用startswith函式進行判斷。str 人生苦短,我用python if len str 2 and str 2 人生 print 以 人生 開頭的字串 else print 不以 人生 開頭的字串 要取...