gpt4 book ai didi

python - 使用带有口音和不同字符的 Beautiful Soup

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:10 25 4
gpt4 key购买 nike

我正在使用 Beautiful Soup 从过去的奥运会中获得奖牌。它因在某些赛事和运动员姓名中使用重音符号而被绊倒。我在网上看到过类似的问题,但我是 Python 的新手,无法将它们应用到我的代码中。

如果我打印我的汤,口音看起来很好。但是当我开始解析汤(并将其写入 CSV 文件)时,重音字符变成乱码。'Louis Perrée' 变成 'Louis Perr√©e'

from BeautifulSoup import BeautifulSoup
import urllib2

response = urllib2.urlopen('http://www.databaseolympics.com/sport/sportevent.htm?sp=FEN&enum=130')
html = response.read()
soup = BeautifulSoup(html)

g = open('fencing_medalists.csv','w"')
t = soup.findAll("table", {'class' : 'pt8'})

for table in t:
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
theText=str(td.find(text=True))
#theText=str(td.find(text=True)).encode("utf-8")
if theText!="None":
g.write(theText)
else:
g.write("")
g.write(",")
g.write("\n")

非常感谢您的帮助。

最佳答案

如果您正在处理 unicode,请始终将从磁盘或网络读取的响应视为字节包而不是字符串。

您的 CSV 文件中的文本可能是 utf-8 编码的,应该先对其进行解码。

import codecs
# ...
content = response.read()
html = codecs.decode(content, 'utf-8')

在将它写入输出文件之前,您还需要将您的 unicode 文本编码为 utf-8。使用 codecs.open 打开输出文件,指定编码。它将透明地为您处理输出编码。

g = codecs.open('fencing_medalists.csv', 'wb', encoding='utf-8')

并对字符串写入代码做如下改动:

    theText = td.find(text=True)
if theText is not None:
g.write(unicode(theText))

编辑: BeautifulSoup 可能会做 automatic unicode decoding ,因此您可以在响应时跳过 codecs.decode

关于python - 使用带有口音和不同字符的 Beautiful Soup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10264937/

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