簡體   English   中英

Python ASCII 編解碼器在寫入 CSV 期間無法編碼字符錯誤

[英]Python ASCII codec can't encode character error during write to CSV

我不完全確定我需要對這個錯誤做些什么。 我認為這與需要添加 .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 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')
  2. \n
\n

  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):

問題在於 python 2 中的 csv 庫。來自 unicodecsv項目頁面

Python 2 的 csv 模塊不能輕松處理 unicode 字符串,導致可怕的“'ascii' codec can't encode characters in position ...”異常。

如果可以,只需安裝 unicodecsv

pip install unicodecsv

import unicodecsv

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

除了Alastair的出色建議之外,我發現最簡單的選擇是使用 python3 而不是 python 2。我的腳本中所需的只是根據 Python3 的語法open語句中的wb更改為簡單的w

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM