2015-09-08 69 views
3

所以我試圖從網站獲取數據並將其解析爲對象。數據由豎線分隔(「|」)。然而,當我使用.split('|')分割我的字符串時,我得到了嘗試在Python 3中拆分字符串,得到「str」不支持緩衝區接口

TypeError: 'str' does not support the buffer interface 

我仍在嘗試學習Python。我已經對這個錯誤進行了一些研究,但是我可以找到與發送或接收數據相關的每個示例,並且有很多我不熟悉的術語。一個解決方案說使用.split(b'|'),但是這不知怎的把我的字符串變成了一個字節,並阻止我在最後一行打印它。

以下是我的代碼。任何幫助你可以提供將不勝感激!

with urllib.request.urlopen('ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqtraded.txt') as response: 
    html = response.read() 
rawStockList = html.splitlines() 

stockList = [] 
for i in rawStockList: 
    stockInfo = i.split('|') 
    try: 
     stockList.append(Stock(stockInfo[1], stockInfo[2], stockInfo[5], stockInfo[10], 0)) 
    except IndexError: 
     pass 
print([str(item) for item in stockList]) 

回答

5

rawStockList的項目實際上是類型byte,因爲response.read()回報是因爲它並不需要知道的編碼。您需要通過編碼將其解碼爲適當的字符串。假設文件使用utf8編碼,則需要如下所示的內容:

for i in rawStockList: 
    stockInfo = i.decode('utf8').split('|') 
+0

謝謝您的幫助解釋! – silverstieff

相關問題