python3 chardetModule.py

"""
模塊:python3 chardetModule.py
功能:Python3 查看網頁、文件、字節串的編碼。
參考:https://blog.csdn.net/wyounger/article/details/98943372
知識點:
1.charsetDetector
"""
# 1.網頁
import urllib.request
import chardet
url = 'http://www.baidu.com'
a = urllib.request.urlopen(url)
encode = chardet.detect(a.read())
print(encode['encoding'])  # utf-8

# 2.文件
print("\n2.")
with open('cs.txt', 'rb') as f:
    print(chardet.detect(f.read(100)))
# {'encoding': 'UTF-8-SIG', 'confidence': 1.0, 'language': ''}

# 3.字節串
print("\n3.")
s = '張三'
print(chardet.detect(s.encode()))
# {'encoding': 'utf-8', 'confidence': 0.7525, 'language': ''}
# print(chardet.detect(s))
# TypeError: Expected object of type bytes or bytearray, got: <class 'str'>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章