and*_*ero 3 python replace runtime-error
我刚刚开始使用Python,我正在尝试制作一个程序,在互联网"www ....../lyrics.txt"打开的屏幕上写一首歌的歌词.我的第一个代码:
import urllib.request
lyrics=urllib.request.urlopen("http://hereIsMyUrl/lyrics.txt")
text=lyrics.read()
print(text)
Run Code Online (Sandbox Code Playgroud)
当我激活这段代码时,它没有给我在网站上写的歌词,它给了我新的行命令'\ r \n'在应该是新行的所有地方并给了我所有的歌词在一个长杂乱的字符串.例如:这里的一些歌词\ r \n这应该已经是下一行了\ r \n等等.
我在互联网上搜索代码,用新行代替'\ r \n'命令并尝试以下方法:
import urllib.request
lyrics=urllib.request.urlopen("http://hereIsMyUrl/lyrics.txt")
text=lyrics.read()
text=text.replace("\r\n","\n")
print(text)
Run Code Online (Sandbox Code Playgroud)
我希望它至少可以替换一些东西,但它给了我一个运行时错误:
TypeError: expected bytes, bytearray or buffer compatible object
Run Code Online (Sandbox Code Playgroud)
我在互联网上搜索了这个错误,但我没有找到任何与从互联网上打开文件有关的内容.
我已经被困在这一点上几个小时,不知道如何继续.请帮忙!提前致谢!
您的示例无效,因为read语句返回的数据是"字节对象".您需要使用适当的编码对其进行解码.另见的文档request.urlopen,file.read和字节数组的操作.
下面给出了一个完整的工作示例:
#!/usr/bin/env python3
import urllib.request
# Example URL
url="http://ntl.matrix.com.br/pfilho/oldies_list/top/lyrics/black_or_white.txt"
# Open URL: returns file-like object
lyrics=urllib.request.urlopen(url)
# Read raw data, this will return a "bytes object"
text=lyrics.read()
# Print raw data
print(text)
# Print decoded data:
print(text.decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4604 次 |
| 最近记录: |