【问题标题】:youtube-dl filename formatting lowercase and dashesyoutube-dl 文件名格式化小写和破折号
【发布时间】:2020-03-26 19:23:15
【问题描述】:

我经常使用youtube-dl 并且有一个非常简单的文件命名方案:只有小写字母,同一组的东西用“-”(减号、破折号等)连接,而不同的东西用“_”(下划线)。

我不喜欢正则表达式,因此,如果可以根据我的命名方案配置youtube-dl config-file 来存储下载的剪辑,我真的很困惑。例如:

视频:

youtube-dl https://www.youtube.com/watch?v=X8uPIquE5Oo

我的 youtube-dl config:

--output '~/videos/%(uploader)s_%(upload_date)s_%(title)s.%(ext)s' --restrict-filenames

我的输出:

Queen_Forever_20111202_Bohemian_Rhapsody_Live_at_Wembley_11-07-1986.mp4

想要的输出:

queen-forever_20111202_bohemian-rhapsody-live-at-wembley-11-07-1986.mp4

注意:manual says 可能有python options,但我无法将它们转移到我的案例中。

【问题讨论】:

    标签: python regex youtube-dl


    【解决方案1】:

    我认为通过字符串格式化选项不可能,但您可以从 python 脚本调用 youtube-dl。因此,使用小型 python 包装器是可能的。

    Youtube DL Documentation

    import youtube_dl
    import os
    
    
    def correct_file_naming(response):
        if response['status'] == 'finished':
            directory = os.path.dirname(response['filename'])
            # Replace `_` with `-` first
            # Then replace `separator` with `_`
            new_filename = os.path.basename(response['filename'])\
                .replace("_", "-")\
                .replace(separator, "_")\
                .lower()
    
            os.rename(response['filename'], os.path.join(directory, new_filename))
    
    
    if __name__ == "__main__":
        # Just a random string that won't appear naturally in the filename.
        # Required since the dynamic fields (e.g. title) are using characters
        # that are going to be used as the seperator when we're done
        separator = '@#@'
        download_path = '~/videos/'
    
        # see link for options:
        # https://github.com/ytdl-org/youtube-dl/blob/3e4cedf9e8cd3157df2457df7274d0c842421945/youtube_dl/YoutubeDL.py#L137-L312
        ydl_opts = {
            'outtmpl': f'{download_path}%(uploader)s{separator}%(upload_date)s{separator}%(title)s.%(ext)s',
            'restrictfilenames': True,
            'progress_hooks': [correct_file_naming]
        }
    
        url = 'https://www.youtube.com/watch?v=X8uPIquE5Oo'
    
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
    
    1. correct_file_naming 在下载过程中会被多次调用。所以if 语句确保它在我们开始尝试重命名文件之前完成。如果过早地这样做会导致一些问题。
    2. 分隔符变量是一个小技巧。它用作临时变量,因为_ 字符存在冲突。您希望分隔符为_,但动态选项(例如标题/上传者)正在使用该字符。因此,在重命名过程中,我们将它们分开,以确保一切正常。

    如果您愿意,您可以通过 python 脚本公开所有参数,因此这只不过是 youtube-dl 代码的一个小包装。然后,只需将它们指向包装器,它就应该可以轻松地集成到您拥有的任何现有脚本中。

    【讨论】:

    • 非常感谢。我不再使用 youtube-dl,因此我无法检查您的代码是如何工作的。我相信你已经测试了代码,所以我对答案进行了评分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多