Python判断文件和字符串编码类型的实例

yipeiwu_com6年前Python基础

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前缀字节
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:
  return 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):
    return 'UTF-8-SIG'
   return code
  except Exception:
   continue
 return '未知的字符编码类型'

说明:file_encoding方法用于判断文件编码类型,参数为文件路径;string_encoding方法用于判断字符串编码类型,参数为字符串对应的字节数据

使用示例:

import coding
file_name = input('请输入待识别文件路径:\n')
encoding = coding.file_encoding(file_name)
print(encoding)

以上这篇Python判断文件和字符串编码类型的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中字符串内置函数的用法总结

capitalize() 首字母大写 a='someword' b=a.capitalize() print(b) —>Someword casefold()&l...

详解python中的模块及包导入

python中的导入关键字:import 以及from  import 1、import   import一般用于导入包以及模块。   不过有个小问题:   (1)当导入的是...

python elasticsearch环境搭建详解

windows下载zip linux下载tar 下载地址:https://www.elastic.co/downloads/elasticsearch 解压后运行:bin/elast...

python两种遍历字典(dict)的方法比较

python以其优美的语法和方便的内置数据结构,赢得了不少程序员的亲睐。其中有个很有用的数据结构,就是字典(dict),使用非常简单。说到遍历一个dict结构,我想大多数人都会想到 fo...

用python 实现在不确定行数情况下多行输入方法

如下所示: stopword = '' str = '' for line in iter(raw_input, stopword): str += line + '\n' pri...