【发布时间】:2019-05-06 02:23:18
【问题描述】:
所以我正在制作一个脚本来读取一堆文本文件(每首歌一个)作为歌词。它的工作原理是您输入歌词短语,脚本会扫描所有可用文件以查找这些歌词并告诉您歌曲的名称。问题是斜线不起作用。我更改了“/”和“\”之间的斜线,但我遇到了错误。
当我使用正斜杠时,我看到以下内容:
"OSError: [Errno 22] 无效参数:' C:/Users/[My 名称]/Desktop/MusicLyricSearch/AllSongs/Old_Town_Road.txt'"
当我放回斜杠时,我得到了错误:
"SyntaxError: (unicode error) 'unicodeescape' 编解码器无法解码字节 在位置 3-4:截断 \UXXXXXXXXXX 转义”。
我看过很多其他关于如何做到这一点的帖子,例如: Searching multiple text files for two strings? 和 (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
所以,第一个链接确实是代码,但我得到了错误
"SyntaxError: (unicode error) 'unicodeescape' 编解码器无法解码字节 在位置 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 编码还是很陌生。
【问题讨论】:
-
使用正斜杠但省略
C:之前的空格。如果还没有完成,你应该通过Python tutorial -
尝试使用反斜杠,但在字符串前添加
r。当您键入 user 时,\U被处理为八字符 unicode 转义码的开头。像这样的东西: open(r'C:\Users[My Name]\Desktop\MusicLyricSearch\AllSongs\results.txt', "w")