关于python3里判断文件编码的问题

qq_40775799 2018-05-12 12:10:59
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类型吗?那我必须判断呢?
...全文
3269 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
text_line = open("fp1.txt").read().encode() 这里第二行的encode是使用python默认的编码ascii方式将str解析成了bytes。然后再判断他的encoding。 encoding = chardet.detect(open(input_path, 'rb').read())['encoding'] 使用rb方式
枫溪迪 2019-07-31
  • 打赏
  • 举报
回复
首先你应该明确,这个是判断编码而不是判断数据类型的,其次,加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)



痴迷、淡然~ 2019-06-17
  • 打赏
  • 举报
回复 1
将读取方式改为 'rb' 模型解决了。
qq_42212319 2018-05-18
  • 打赏
  • 举报
回复
我的环境验证是可以的

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧