python3 functools.cmp_to_key 统计视频时长

cmp_to_key 简要说明

cmp_to_key把旧版本格式的比较方法转化成key 方法,主要用来适配支持排序相关的方法例如soted, max 等方法

 

视频统计中使用cmp_to_key

下面使用视频时长统计案例代码

注意案例中使用了moviepy模块,请使用 pip install moviepy 进行安装即可

# coding=utf-8

from moviepy.editor import VideoFileClip
import os
import sys
import re
import functools



count = 0

def time_convert(seconds):
    """
        将秒换成合适的时间,如果超过一分钟就换算成"分钟:秒",如果是小时,就换算成"小时:分钟:秒"单位换算
    """
    print(f'时间换算{seconds}')
    M,H = 60,3600
    if seconds < M:
        return f'00:00:0{seconds}' if seconds < 10 else f'00:00:{str(seconds)}'
    elif seconds < H:
        _M = int(seconds/M)
        _S = int(seconds%M)
        return f'00:{f"0{_M}" if _M < 10 else str(_M)}:{f"0{_S}" if _S < 10 else str(_S)}'
    else:
        _H = int(seconds/H)
        _M = int(seconds%H/M)
        _S = int(seconds%H%M)
        return f'{f"0{_H}" if _H < 10 else str(_H)}:{f"0{_M}" if _M < 10 else str(_M)}:{f"0{_S}" if _S < 10 else str(_S)}'


def write_video_time(video_file):
    """
    统计计算视频时长
    """
    global count
    ext_name = os.path.splitext(video_file)
    if ext_name[1] == ".mp4" or ext_name[1] == ".avi" or ext_name[1] == ".wmv":
        clip = VideoFileClip(video_file)
        count += round(clip.duration / 60)
        v_time = time_convert(clip.duration)
        rfile.write(os.path.splitext(os.path.basename(video_file))[0] + "\t" + v_time+'\r\n')
        close_clip(clip)

def close_clip(clip):
    """
    关闭视频文件句柄
    """
    try:
        clip.reader.close()
        del clip.reader
        if clip.audio != None:
                clip.audio.reader.close_proc()
                del clip.audio
        del clip
    except Exception as e:
            sys.exc_clear()

# 主要解决 视频名字不规则问题:  ["1.多线程.mp4",'02.多进程.mp4','3.正则.mp4'],出现排混乱问题
# 处理的视频序号不超过100的
def cmp(x,y):
    # 处理视频名称数字编号只有一个数字的情况
    if re.match(r'\d[^\d]',x):
        x = '0'+x
    if re.match(r'\d[^\d]',y):
        y = '0'+y
    # 根据大小返回 1 -1 0
    if x>y:
        return 1
    if x==y:
        return 0
    if x<y:
        return -1

def traverse_dir(file_dir):
    # 递归遍历统计视频时长
    if os.path.isdir(file_dir):
        file_list = os.listdir(file_dir)
        # 指定我们自己的排序规则
        file_list = sorted(file_list,key=functools.cmp_to_key(cmp) )
        for video in file_list:
            if os.path.isdir(file_dir + "/" + video):
                traverse_dir(file_dir + "/" + video)
            else:
                write_video_time(file_dir + "/" + video)


video_dir = "./"
rfile = open("./vl.txt", "w",encoding='utf8')
traverse_dir(video_dir)
rfile.close()

学IT,上博学谷

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值