gpt4 book ai didi

python - python中如何将UTF-8编码转换为符号字符

转载 作者:行者123 更新时间:2023-11-30 23:15:47 25 4
gpt4 key购买 nike

我使用 python 的 urllib.request API 抓取了一些网页,并将读取的行保存到一个新文件中。

        f = open(docId + ".html", "w+")
with urllib.request.urlopen('http://stackoverflow.com') as u:
s = u.read()
f.write(str(s))

但是当我打开保存的文件时,我看到了很多诸如\xe2\x86\x90之类的字符串,这本来是原始页面中的箭头符号。看起来是符号的UTF-8编码,但是如何将编码转换回符号呢?

最佳答案

您的代码已损坏:u.read() 返回bytes 对象。 str(bytes_object) 返回对象的字符串表示(字节文字的样子)——您不希望在这里使用它:

>>> str(b'\xe2\x86\x90')
"b'\\xe2\\x86\\x90'"

按原样将字节保存在磁盘上:

import urllib.request

urllib.request.urlretrieve('http://stackoverflow.com', 'so.html')

或者以二进制模式打开文件:'wb'并手动保存:

import shutil
from urllib.request import urlopen

with urlopen('http://stackoverflow.com') as u, open('so.html', 'wb') as file:
shutil.copyfileobj(u, file)

或将字节转换为 Unicode 并使用您喜欢的任何编码将它们保存到磁盘。

import io
import shutil
from urllib.request import urlopen

with urlopen('http://stackoverflow.com') as u, \
open('so.html', 'w', encoding='utf-8', newline='') as file, \
io.TextIOWrapper(u, encoding=u.headers.get_content_charset('utf-8'), newline='') as t:
shutil.copyfileobj(t, file)

关于python - python中如何将UTF-8编码转换为符号字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28104377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com