blackantt 发表于 2024-3-25 14:40:37

“如果不存在”, 只能用try来避开?

if transcript_list.find_manually_created_transcript(['en']) is not None:
      print('man have-----------------')
elif transcript_list.find_generated_transcript(['en']):
      print('gen have -----------------')
else:
      continue


下面是告警
ytube_transcript_api._errors.NoTranscriptFound:
Could not retrieve a transcript for the video https://www.ytube.com/watch?v=DbkEDAqCxeo! This is most likely caused by:

No transcripts were found for any of the requested language codes: ['en']

For this video (DbkEDAqCxeo) transcripts are available in the following languages:

(MANUALLY CREATED)
None

(GENERATED)
- en ("English (auto-generated)")

FishC 发表于 2024-3-25 14:40:48

在处理这种不存在的情况时,使用`try-except`块是一种常见的方法。通过将可能引发异常的代码放在`try`块中,然后使用`except`块来处理异常。

对于你的代码,可以使用`try-except`块来处理找不到转录文本的异常。例如:

try:
    if transcript_list.find_manually_created_transcript() is not None:
      print('man have-----------------')
    elif transcript_list.find_generated_transcript():
      print('gen have -----------------')
    else:
      continue
except ytube_transcript_api._errors.NoTranscriptFound as e:
    print(e)

在上面的代码中,如果`find_manually_created_transcript()`或`find_generated_transcript()`抛出`ytube_transcript_api._errors.NoTranscriptFound`异常,程序将捕获该异常并打印出错误消息。

请注意,在你的代码中我用`e`代表异常对象,你可以根据需要对其进行处理,比如输出更详细的错误信息或采取其他适当的行动。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: “如果不存在”, 只能用try来避开?