UnicodeEncodeError: 'ascii' 编解码器无法对位置 6 中的字符 u'\\u2019' 进行编码:序号不在范围内 (128)

新手上路,请多包涵

我正试图从 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

原文由 dtrinh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 716
2 个回答

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() e638ee8382dae412956bd506bf70-cfunction388- 的别名)。

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

原文由 Laurent LAPORTE 发布,翻译遵循 CC BY-SA 3.0 许可协议

您正在将非 ascii 字符写入 csv 输出文件。确保使用允许对字符进行编码的适当字符编码打开输出文件。一个安全的选择通常是 UTF-8。尝试这个:

 with open('ListingsPull-Amsterdam.csv', 'a', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(rest_array)

编辑 这是针对 Python 3.x 的,抱歉。

原文由 Irmen de Jong 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题