Python 3中怎么查看字符编码

这篇文章将为大家详细讲解有关Python 3中怎么查看字符编码,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、查看网页编码


   
     
   
   
  

#coding=utf-8


import urllib.request


import chardet


url = 'http://www.baidu.com'


a = urllib.request.urlopen(url)


encode = chardet.detect(a.read())


print(encode['encoding'])

二、查看文件内容编码


   
     
   
   
  

#假设存在一个a.txt的文件


f = open('a.txt', 'rb')


print(chardet.detect(f.read(100)))

三、查看某个字符串编码


   
     
   
   
  

import chardet


s = '张三'


print(chardet.detect(str.encode(s)))


输出信息:{'encoding': 'utf-8', 'confidence': 0.7525, 'language': ''}

Tips:


   
     
   
   
  

chardet.detect 在查看字符串传的编码时,必须要把字符串encode后,才能查看当前字符串编码格式

关于Python 3中怎么查看字符编码就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。