【问题标题】:How to determine how a (downloaded) byte string is encoded in python?如何确定(下载的)字节字符串如何在 python 中编码?
【发布时间】:2021-07-08 18:40:27
【问题描述】:

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

from urllib.request import urlopen
url = "http://export.arxiv.org/e-print/supr-con/9608001"
with urllib.request.urlopen(url) as response:
    data = response.read()
    filename = 'test.txt'
    file_ = open(filename, 'wb')
    file_.write(data)
    file_.close()

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

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

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

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

【问题讨论】:

  • 您的data 包含文件签名b'\x1f\x8b' 即GZIP 压缩文件...
  • 检查print( response.headers ),您会看到Content-Encoding: x-gzip,这表明它发送使用gzip 压缩的数据(以便更快地发送),您必须解压缩它。当您在浏览器中运行 URL 时,浏览器会自动为您解压缩。

标签: python decode encode


【解决方案1】:

申请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': ''}

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2012-12-20
    • 2013-04-01
    • 2012-07-07
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多