2017-02-05 57 views
0

我試圖使用python CSV模塊將一些新聞標題寫入CSV,並且似乎在標題中有一個撇號,例如'無論如何,Snapchat有什麼好處?',那麼編碼錯誤就會顯現出來。Python Sqlite無法正確寫入字符串中存在「'」

的錯誤是如下:

enter image description here

代碼:

enter image description here

是否有關於這個錯誤有什麼建議或有什麼想法?

+0

問題不是CSV但終端/主機在你的系統中(可能是Windows中)因爲它不顯示'UTF-8',並且它有轉換它的問題。 [將Windows控制檯的默認代碼頁更改爲UTF-8](http://superuser.com/questions/269818/change-default-code-page-of-windows-console-to-utf-8) – furas

+0

感謝您回覆Furas!我發現這是因爲Python CSV模塊不支持Unicode ...這是一篇很有用的文章。 [鏈接](http://stackoverflow.com/questions/3224268/python-unicode-encode-error) –

回答

1

Python2.7 csv模塊不能本地處理unicode。但docs有一個如何在類UnicodeWriter中完成的例子。你也可以嘗試python3,因爲csv模塊會在本地處理unicode。

這個片段已經被無恥地從文檔撕開我聯繫

class UnicodeWriter: 
    """ 
    A CSV writer which will write rows to CSV file "f", 
    which is encoded in the given encoding. 
    """ 

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): 
     # Redirect output to a queue 
     self.queue = cStringIO.StringIO() 
     self.writer = csv.writer(self.queue, dialect=dialect, **kwds) 
     self.stream = f 
     self.encoder = codecs.getincrementalencoder(encoding)() 

    def writerow(self, row): 
     self.writer.writerow([s.encode("utf-8") for s in row]) 
     # Fetch UTF-8 output from the queue ... 
     data = self.queue.getvalue() 
     data = data.decode("utf-8") 
     # ... and reencode it into the target encoding 
     data = self.encoder.encode(data) 
     # write to the target stream 
     self.stream.write(data) 
     # empty queue 
     self.queue.truncate(0) 

    def writerows(self, rows): 
     for row in rows: 
      self.writerow(row) 

然後,你可以把它做

writer = UnicodeWriter(open("foo", "w")) 
writer.writerow(['1', 'bar']) 
+0

感謝您回覆格雷格!你是完全正確的。當我抓取標題時,我通過添加'title = content.text.encode('ascii','ignore')'來解決這個問題。 –

+0

肯定np。 Upvote,如果你喜歡它:) – Greg

相關問題