我希望使用 if 和 elif 语句下载带字幕或不带字幕的视频。目前只有我的第一个选项有效,当我选择第二个选项时,尽管有第二个选项,第一个选项再次运行。目前,我的实现是:import youtube_dldef switch_demo(x): switcher = { 1: "With Subtitles", 2: "Without Subtitles", } return switcher.get(x,"Invalid Option")x = int(input("Select the option\n1.With Subtitles\n2.Without Subtitles\n\n"))print(switch_demo(x))link=input('Please enter a url link\n')if switch_demo(1): ydl_opts = {"writesubtitles": True} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([link])elif switch_demo(2): ydl_opt = {} with youtube_dl.YoutubeDL(ydl_opt) as ydl: ydl.download([link])我希望能够下载带或不带字幕的视频,这两个选项都可以工作。
2 回答

海绵宝宝撒
TA贡献1809条经验 获得超8个赞
您使用函数 switch_demo 返回值作为驱动 if 语句的标准。问题是python将任何非空值视为真语句,这就是为什么您的第二个选择永远不会运行的原因

DIEA
TA贡献1820条经验 获得超2个赞
你没有传递x给函数,所以你永远不会改变结果,也就是说我已经重写了你的代码。
import youtube_dl
switcher = {
1: "With Subtitles",
2: "Without Subtitles",
}
def switch_demo(x):
return switcher.get(x, False)
print("Select an option")
print(*["#{} {}".format(i + 1, switcher[i + 1]) for i in range(max(switcher.keys()))], sep = "\n")
option = int(input("> "))
link = input('Please enter a url link\n')
useSubtitles = switch_demo(x)
ydl_opts = {"writesubtitles": useSubtitles}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([link])
添加回答
举报
0/150
提交
取消