gpt4 book ai didi

python - 统一码编码错误 : 'ascii' codec can't encode character u'\u2019' in position 6: ordinal not in range(128)

转载 作者:太空狗 更新时间:2023-10-29 22:07:34 25 4
gpt4 key购买 nike

我正在尝试从 TripAdvisor 中提取阿姆斯特丹 500 家餐厅的列表;然而,在第 308 家餐厅之后,我收到以下错误:

Traceback (most recent call last):
File "C:/Users/dtrinh/PycharmProjects/TripAdvisorData/LinkPull-HK.py", line 43, in <module>
writer.writerow(rest_array)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 6: ordinal not in range(128)

我尝试了一些在 StackOverflow 上找到的东西,但目前没有任何效果。我想知道是否有人可以看一下我的代码,看看是否有任何潜在的很棒的解决方案。

        for item in soup2.findAll('div', attrs={'class', 'title'}):
if 'Cuisine' in item.text:
item.text.strip()
content = item.findNext('div', attrs=('class', 'content'))
cuisine_type = content.text.encode('utf8', 'ignore').strip().split(r'\xa0')
rest_array = [account_name, rest_address, postcode, phonenumber, cuisine_type]
#print rest_array
with open('ListingsPull-Amsterdam.csv', 'a') as file:
writer = csv.writer(file)
writer.writerow(rest_array)
break

最佳答案

rest_array 包含 unicode 字符串。当您使用 csv.writer 写入行时,您需要序列化字节字符串(您使用的是 Python 2.7)。

我建议你使用“utf8”编码:

with open('ListingsPull-Amsterdam.csv', mode='a') as fd:
writer = csv.writer(fd)
rest_array = [text.encode("utf8") for text in rest_array]
writer.writerow(rest_array)

注意:请不要将 file 用作变量,因为您隐藏了内置函数 file()(open 的别名() 函数)。

如果您想使用 Microsoft Excel 打开此 CSV 文件,您可以考虑使用其他编码,例如“cp1252”(它允许 u"\u2019"字符)。

关于python - 统一码编码错误 : 'ascii' codec can't encode character u'\u2019' in position 6: ordinal not in range(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40619675/

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