我编写了一个程序,可以帮助我在歌曲的歌词之间快速切换。它从文件中读取歌词.lyr
并将它们打印出来给我。
这是一个简化版本,没有任何附加功能,例如edit_line()
. 此代码仍然出现问题。
import os
class Lyrics:
def __init__(self, file):
'''Initialize new Lyrics object'''
self.file = file.replace("/", "\\")
self.path = self.file.rsplit("\\", 1)[0] + "\\"
self.suffix = "." + self.file.rsplit(".")[-2]
self.name = self.file\
.replace(self.path, "")\
.replace(".lyr", "")\
.replace(self.suffix, "")
def draw(self):
'''Draw lyrics on user's screen'''
maxlen = len(str(len(self.content)))
print("[[ %s ]]"%self.name)
for i,line in enumerate(self.content):
print("%i %s"%(i+1, line), end="")
def play(self):
'''View lyrics'''
with open(self.file, "r") as f:
self.content = f.readlines()
#os.system("cls")
self.draw()
input("[[ Press enter to quit ... ]]")
def main(directory):
# Get lyric files from directory
lyric_files = []
for file in os.listdir(directory):
if file.endswith(".lyr"):
lyric_files.append(Lyrics(directory + file))
# Create variable for showing messages to user
msg = ""
# Main loop
while True:
# Print lyric files
#os.system("cls")
for i, file in enumerate(lyric_files):
print("%i :: %s"%(i+1, file.name))
# Handle input
cmd = input("%s>"%msg)
if cmd == "bye":
break
try:
lyric_files[int(cmd)-1].play()
msg = ""
except ValueError:
msg = "ValueError: Input must be an integer\n"
except IndexError:
msg = "IndexError: Integer must be between 1 and %i\n"%len(lyric_files)
if __name__ == "__main__":
main("E:\\documents\\lyrics\\")
中的文件E:\documents\lyrics\
使用以下格式命名:
Artist - Song.format.lyr`
例如:
E:\documents\lyrics\Adele - Set Fire to the Rain.mp3.lyr
当我打开程序时,它会按原样列出所有文件,然后要求我输入:
1 :: Adele - Set Fire to the Rain
2 :: Eminem - Not Afraid
3 :: Nicki Minaj - Starships
>
Set Fire to the Rain
当我用 index打开歌词时1
,它们打开得非常完美。但是,当我尝试打开歌词时Not Afraid
,我可以在输出中看到大约 50 行歌词,而歌词文件实际上是 120 行左右。然后它要求我输入来自main()
函数的输入,ValueError
如下所示:
1 first_line_in_lyrics
2 second_line_in_lyrics
i ...
42 fourty_second_line_in_lyrics
43 fourty_third_line_in_lyrics
1 :: Adele - Set Fire to the Rain
2 :: Eminem - Not Afraid
3 :: Nicki Minaj - Starships
ValueError: Input must be an integer
>
这些文件彼此几乎相同(当然歌词不同)。该程序在 IDLE 上运行良好,但在 python 命令行上却不行。