win10
pycharm社區版
python3
pip最新下載的chardet
附帶txt是臉滾鍵盤
源程式如下:
import chardet
text_line = open("fp1.txt").read()
print(type(text_line))
print(chardet.detect(text_line))
運行結果
Traceback (most recent call last):
<class 'str'>
File "text.py", line 4, in <module>
print(chardet.detect(text_line))
File "D:\python\lib\site-packages\chardet\__init__.py", line 34, in detect
'{0}'.format(type(byte_str)))
TypeError: Expected object of type bytes or bytearray, got: <class 'str'>
Process finished with exit code 1
但如果第二行寫
text_line = open("fp1.txt").read().encode()
確實可以通過,還有啥意義?
chardet.detec真的不可以接受str型別嗎?那我必須判斷呢?
uj5u.com熱心網友回復:
我的環境驗證是可以的uj5u.com熱心網友回復:
將讀取方式改為 'rb' 模型解決了。uj5u.com熱心網友回復:
首先你應該明確,這個是判斷編碼而不是判斷資料型別的,其次,加encode只是將其變成了位元組,這個判斷是只能夠接受位元組而不能接收字符型別的,現在
import json
import chardet
dict1 = {'city':'北京','name': 'xaio'}
#json.dumps 默認ascii編碼
jsondict = json.dumps(dict1)
print('jsonlist=',jsonlist)
print('jsondict=',jsondict)
#禁止ascii編碼后默認utf-8
jsondict1 = json.dumps(dict1,ensure_ascii=False)
print(jsondict1)
#ascii
ss = chardet.detect(json.dumps(dict1).encode())
print(ss)
#utf-8
ss = chardet.detect(json.dumps(dict1,ensure_ascii=False).encode())
print(ss)
uj5u.com熱心網友回復:
text_line = open("fp1.txt").read().encode() 這里第二行的encode是使用python默認的編碼ascii方式將str決議成了bytes。然后再判斷他的encoding。encoding = chardet.detect(open(input_path, 'rb').read())['encoding'] 使用rb方式
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/71972.html
上一篇:flask子模板使用父模板的變數
下一篇:懵了
