【问题标题】:Python ASCII codec can't encode character error during write to CSVPython ASCII 编解码器在写入 CSV 期间无法编码字符错误
【发布时间】:2016-01-01 14:07:20
【问题描述】:

我不完全确定我需要对这个错误做些什么。我认为这与需要添加 .encode('utf-8') 有关。但我不完全确定这是否是我需要做的,也不应该在哪里应用它。

错误是:

line 40, in <module>
writer.writerows(list_of_rows)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 1
7: ordinal not in range(128)

这是我的 python 脚本的基础。

import csv
from BeautifulSoup import BeautifulSoup

url = \
'https://dummysite'

response = requests.get(url)

html = response.content

soup = BeautifulSoup(html)

table = soup.find('table', {'class': 'table'})

list_of_rows = []
for row in table.findAll('tr')[1:]:
list_of_cells = []
for cell in row.findAll('td'):
    text = cell.text.replace('[','').replace(']','')
    list_of_cells.append(text)
list_of_rows.append(list_of_cells)

outfile = open("./test.csv", "wb")
writer = csv.writer(outfile)
writer.writerow(["Name", "Location"])
writer.writerows(list_of_rows)

【问题讨论】:

    标签: python csv url utf-8 beautifulsoup


    【解决方案1】:

    问题在于 python 2 中的 csv 库。 来自 unicodecsv project page

    Python 2 的 csv 模块不容易处理 unicode 字符串,导致可怕的“‘ascii’编解码器无法对位置中的字符进行编码……”异常。

    如果可以,只需安装 unicodecsv

    pip install unicodecsv

    import unicodecsv
    
    writer = unicodecsv.writer(csvfile)
    writer.writerow(row)
    

    【讨论】:

      【解决方案2】:

      Python 2.x CSV 库已损坏。你有三个选择。按复杂程度排列:

      1. 编辑:见下文使用固定库https://github.com/jdunck/python-unicodecsv (pip install unicodecsv)。用作替代品 - 示例:

        with open("myfile.csv", 'rb') as my_file:    
            r = unicodecsv.DictReader(my_file, encoding='utf-8')
        

      1. 阅读有关 Unicode 的 CSV 手册:https://docs.python.org/2/library/csv.html(见底部示例)

      2. 手动将每个项目编码为 UTF-8:

        for cell in row.findAll('td'):
            text = cell.text.replace('[','').replace(']','')
            list_of_cells.append(text.encode("utf-8"))
        

      编辑,我发现python-unicodecsv在读取UTF-16时也坏了。它抱怨任何 0x00 字节。

      改为使用https://github.com/ryanhiebert/backports.csv,它更类似于Python 3 实现并使用io 模块..

      安装:

      pip install backports.csv
      

      用法:

      from backports import csv
      import io
      
      with io.open(filename, encoding='utf-8') as f:
          r = csv.reader(f):
      

      【讨论】:

      • 哦哇不知道 CSV 库在 python 中被破坏了。非常感谢!这是一个巨大的帮助
      • 为什么这个投票还不够?我似乎有人使用各种解决方法来解决这个问题,老实说,没有什么比简单地使用“unicodecsv”模块更好。
      【解决方案3】:

      除了Alastair 的出色建议之外,我发现最简单的选择是使用python3 而不是python 2。我的脚本中所需的只是将open 语句中的wb 更改为简单的@ 987654325@accordance with Python3's syntax.

      【讨论】:

        猜你喜欢
        • 2015-02-03
        • 2019-09-01
        • 2017-03-31
        • 2016-04-29
        • 1970-01-01
        • 2019-02-03
        • 1970-01-01
        • 2016-01-04
        • 1970-01-01
        相关资源
        最近更新 更多