因此,我正在制作一个脚本,读取一堆文本文件(每首歌一个)的歌词。它的工作原理是输入一个歌词短语,脚本扫描这些歌词的所有可用文件,并告诉你歌曲的名字。问题是这些斜线不起作用。我在"/“和"\”之间更改斜杠,但遇到了错误。
当我使用正斜杠时,我会看到以下内容:
“Name/Desktop/MusicLyricSearch/AllSongs/Old_Town_Road.txt'”:Errno 22无效参数:‘C:/User/My OSError
当我放回斜杠时,我得到了一个错误:
"SyntaxError:(unicode错误)‘独角形转义’编解码器无法解码位置3-4的字节:截断\UXXXXXXXX转义“。
我见过许多关于如何做到这一点的其他帖子:Searching multiple text files for two strings?和(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
所以,第一个链接实际上是代码,但是我得到了错误
"SyntaxError:(unicode错误)‘独角形转义’编解码器无法解码位置3-4的字节:截断\UXXXXXXXX转义“
修复这个问题的第二个链接也没有真正的帮助
这是我的密码:
from os import listdir
lyricSearch = input("Input the phrase from the song: ")
with open("C:/Users/[My Name]/Desktop/MusicLyricSearch/AllSongs/results.txt", "w") as f:
for filename in listdir("C:/Users/[My Name]/Desktop/MusicLyricSearch/AllSongs"):
with open(" C:/Users/Traner/Desktop/MusicLyricSearch/AllSongs/" + filename) as currentFile:
lyrics = currentFile.read()
if(lyricSearch in lyrics):
f.write("The song is", filename)
else:
f.write("Error: Could not find lyrics in any songs")我希望得到的代码,以改变我的,它显示给我的文件名的歌词,而不是我得到的错误。
正如您可能知道的,因为我基本上复制了代码,所以我对python的编码非常陌生。
发布于 2019-05-06 03:00:58
from os import listdir
lyricSearch = input("Input the phrase from the song: ")
with open(r"C:\Users\[My Name]\Desktop\MusicLyricSearch\AllSongs\results.txt", "w") as f:
for filename in listdir(r"C:\Users\[My Name]\Desktop\MusicLyricSearch\AllSongs"):
with open(r"C:\Users\Traner\Desktop\MusicLyricSearch\AllSongs\" + filename) as currentFile:
lyrics = currentFile.read()
if(lyricSearch in lyrics):
f.write("The song is", filename)
else:
f.write("Error: Could not find lyrics in any songs")此错误来自编写\U时发生的\User。这充当了8个字符unicode转义的开始,但是由于您继续使用文件路径,python无法解释该转义代码并发出错误。字符串开头的r强制将其视为原始字符串,因此不考虑unicode转义。
https://stackoverflow.com/questions/55998074
复制相似问题