我正试着从强力球获胜号码文件中读出: http://www.powerball.com/powerball/winnums-text.txt
我试着一行一行地得到它,我有这样的代码:
import urllib.request
with urllib.request.urlopen("http://www.powerball.com/powerball/winnums-text.txt") as file:
next(file)
for line in file:
line.lstrip("b'")
line.rstrip(" \r\n'")
print(line)
文件中的每一行都这样打印出来:
b'12/06/1997 15 26 28 08 43 36 \r\n'
b'12/03/1997 18 09 14 47 42 32 \r\n'
b'11/29/1997 11 27 13 02 31 23 \r\n'
b'11/26/1997 15 46 34 23 40 35 \r\n'
b'11/22/1997 22 31 03 07 14 02 \r\n'
我得到一个错误:
File "powerball.py", line 5, in <module>
line.lstrip("b'")
TypeError: 'str' does not support the buffer interface
我试图摆脱多余的字符,并使行如下:
12/06/1997 15 26 28 08 43 36
我该怎么解决这个问题?你知道吗
line
是字节序列,而不是字符串。使用str
函数将其转换为字符串。你知道吗正如有人已经提到的,文件是以二进制模式读取的。您需要将字符串转换为文本编码格式。 您可以通过以下方法解决此问题:
这应该给你你所期望的行为。你知道吗
我强烈建议对这种IO使用pandas,它将在一行代码中处理http请求、解析和所有内容;另外,您还可以使用它进行数据分析:
相关问题 更多 >
编程相关推荐