微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何确定下载的字节字符串在python中是如何编码的?

如何解决如何确定下载的字节字符串在python中是如何编码的?

我正在尝试下载一个文件并将其写入磁盘,但不知何故我迷失在编码解码领域。

import chardet
the_encoding = chardet.detect(data)['encoding']

这里的数据是一个字节串。如果我检查文件,我会发现一堆奇怪的字符。我试过了

$ gcc --version
gcc (GCC) 11.1.0
copyright (C) 2021 Free Software Foundation,Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or fitness FOR A PARTIculaR PURPOSE.
$ gcc --version | head -1 | awk '{for(i=1;i<=NF;i++){ if(match($i,/^[0-9]\.[0-9]\.[0-9]$/))  {print $i; exit 0}}}'
$

但这会导致无。所以我真的不知道我下载的数据是如何编码的?

如果我只是在浏览器中输入“http://export.arxiv.org/e-print/supr-con/9608001”,它会下载一个我可以用文本编辑器查看的文件,它非常好。 tex 文件

解决方法

应用 python-magic library

python-magiclibmagic 文件类型的 Python 接口 识别库。 libmagic 通过检查识别文件类型 它们的标题根据预定义的文件类型列表。这 功能通过 Unix 命令暴露给命令行 file

评论脚本(适用于 Windows 10,Python 3.8.6):

# stage #1: read raw data from a url
from urllib.request import urlopen
import gzip
url = "http://export.arxiv.org/e-print/supr-con/9608001"
with urlopen(url) as response:
    rawdata = response.read()

# stage #2: detect raw data type by its signature
print("file signature",rawdata[0:2])
import magic
print( magic.from_buffer(rawdata[0:1024]))

# stage #3: decompress raw data and write to a file
data = gzip.decompress(rawdata)
filename = 'test.tex'
file_ = open(filename,'wb')
file_.write(data)
file_.close()

# stage #4: detect encoding of the data ( == encoding of the written file)
import chardet
print( chardet.detect(data))

结果.\SO\68307124.py

file signature b'\x1f\x8b'
gzip compressed data,was "9608001.tex",last modified: Thu Aug  8 04:57:44 1996,max compression,from Unix
{'encoding': 'ascii','confidence': 1.0,'language': ''}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。