尝试在Python 3中分割字符串,出现“str不支持缓冲区接口”的错误。

4

我正在尝试从一个网站获取数据并将其解析为一个对象。该数据由竖线符号(“|”)分隔。然而,当我使用.split('|')来拆分字符串时,结果是:

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])
1个回答

8

rawStockList中的项实际上是byte类型,因为response.read()返回的是这种类型,因为它并不知道编码方式。你需要通过解码将其转换为适当的字符串。假设文件以utf8编码,你需要像这样:

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

感谢您的帮助说明! - catsitter1029

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接