2015-10-05 80 views
5

我不完全確定我需要做什麼來解決這個錯誤。我認爲它需要添加.encode('utf-8')。但我不完全確定這是我需要做什麼,也不應該在哪裏應用這個。在寫入CSV期間,Python ASCII編解碼器無法編碼字符錯誤

的錯誤是:

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) 

回答

15

Python 2.x CSV庫已損壞。你有三個選擇。爲了複雜的:

  1. 編輯:請參閱下面 使用固定庫 https://github.com/jdunck/python-unicodecsvpip install unicodecsv)。使用作爲下拉更換 - 實例:

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

  • 閱讀CSV手冊關於Unicode的:https://docs.python.org/2/library/csv.html(參見在底部示例)

  • 手動編碼每個項目爲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): 
    
    +0

    哦,哇,不知道CSV庫在Python中被破壞。非常感謝你!這是一個巨大的幫助 – paintball247

    +2

    爲什麼這不夠投票?我似乎有人使用各種解決方法來解決這個問題,說實話,沒有比簡單使用「unicodecsv」模塊更好的了。 –

    0

    我發現最簡單的選項,除了Alastair的優秀建議,要使用python3而不是python 2.所有它需要在我的scr ipt將open聲明中的wb更改爲accordance with Python3's syntax中的w

    相關問題