gpt4 book ai didi

python - 尝试在 Python 3 中拆分字符串,得到 'str' 不支持缓冲区接口(interface)

转载 作者:太空宇宙 更新时间:2023-11-03 13:15:13 24 4
gpt4 key购买 nike

所以我试图从网站获取数据并将其解析为一个对象。数据由竖线(“|”)分隔。但是,当我使用 .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])

最佳答案

rawStockList 中的项目实际上是 byte 类型,因为 response.read() 返回它,因为它不需要知道编码。您需要通过使用编码对其进行解码来将其转换为正确的字符串。假设文件是​​用 utf8 编码的,你需要这样的东西:

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

关于python - 尝试在 Python 3 中拆分字符串,得到 'str' 不支持缓冲区接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32448775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com