Python3 代码优化:新增压缩率计算并确保运行无错误
Python3 代码优化:新增压缩率计算并确保运行无错误
本文介绍了如何修改 Python3 代码,新增压缩率计算功能,并确保代码在执行过程中不会出现错误。代码使用 mediainfo 获取视频信息,并计算文件大小与时长的比率作为压缩率,并将信息写入 Excel 文件。
代码修改部分
import os
import re
import subprocess
import openpyxl
import math
from openpyxl.styles import Font, PatternFill, Alignment
# 支持的视频格式
supported_formats = ['.mp4', '.avi', '.mkv', '.wmv', '.mov', '.flv', '.m2ts', '.ts', '.rm', '.rmvb',
'.vob', '.3gp', '.webm', '.hdmov', '.mp4v', '.mpv4', '.divx', '.xvid', '.f4v',
'.mpeg', '.asf', '.asx', '.m2t']
# 需要处理的视频文件夹
video_folder = input('请输入要文件路径:')
# 输出Excel文件夹路径
excel_folder = '.'
# 输出Excel文件名
excel_file = 'video_info.xlsx'
# 正则表达式匹配码率数据中的空格
pattern = re.compile(r'(\d+)\s+(\d+)')
# 创建Excel文件
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Video Info'
# 设置表头样式
header_font = Font(bold=True, color='800080') # 紫色
header_fill = PatternFill('solid', fgColor='C5E0B4')
header_alignment = Alignment(horizontal='center', vertical='center')
headers = ['文件名', '文件路径', '格式', '大小', '时长', '分辨率', '码率', '帧率', '音频码率', '音频采样率', '音频语言', '压缩率']
for col, header in enumerate(headers, start=1):
cell = ws.cell(row=1, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = header_alignment
# 锁定表头
ws.freeze_panes = 'A2'
# 获取视频文件列表(包括子目录)
video_files = []
for root, dirs, files in os.walk(video_folder):
for file in files:
for format in supported_formats:
if file.endswith(format):
video_files.append(os.path.join(root, file))
break
# 遍历所有视频文件,获取视频信息、音频信息和音频语言,并写入Excel文件
for row, video_file in enumerate(video_files, start=2):
# 获取文件名
file_name = os.path.basename(video_file)
# 获取文件大小并进行单位换算
size = os.path.getsize(video_file)
if size < 1024:
size_str = f'{size} B'
elif size < 1024 * 1024:
size_str = f'{size / 1024:.2f} KiB'
elif size < 1024 * 1024 * 1024:
size_str = f'{size / 1024 / 1024:.2f} MiB'
else:
size_str = f'{size / 1024 / 1024 / 1024:.2f} GiB'
# 使用mediainfo获取视频信息 / 音频信息和音频语言
video_result = subprocess.run(['mediainfo', '--Inform=Video;%Format%|%Width%x%Height%|%BitRate/String%|%FrameRate%|%Duration/String3%', video_file], stdout=subprocess.PIPE)
video_output = video_result.stdout.decode().strip()
audio_result = subprocess.run(['mediainfo', '--Inform=Audio;%BitRate/String%|%SamplingRate/String%|%Language/String%', video_file], stdout=subprocess.PIPE)
audio_output = audio_result.stdout.decode().strip()
# 解析输出结果
format, resolution, bitrate, framerate, duration = video_output.split('|')
audiobitrate, audiosamplingrate, audiolang = audio_output.split('|')
# 时长取整
duration = duration.split('.')[0]
h, m, s = duration.split(':')
duration = f'{h}:{m}:{math.ceil(float(s))}'
# 使用正则表达式替换码率数据中第一个数字和第二个数字之间的空格
bitrate = re.sub(pattern, r'\1\2', bitrate)
# 增加compress项
compress = size / float(duration)
# 写入Excel文件
ws.cell(row=row, column=1, value=file_name)
ws.cell(row=row, column=2, value=os.path.dirname(video_file)) # 写入文件夹路径
ws.cell(row=row, column=3, value=format)
ws.cell(row=row, column=4, value=size_str) # 写入文件大小
ws.cell(row=row, column=5, value=duration)
ws.cell(row=row, column=6, value=resolution)
ws.cell(row=row, column=7, value=bitrate)
ws.cell(row=row, column=8, value=framerate)
ws.cell(row=row, column=9, value=audiobitrate)
ws.cell(row=row, column=10, value=audiosamplingrate)
ws.cell(row=row, column=11, value=audiolang)
ws.cell(row=row, column=12, value=compress) # 写入compress项
# 自动调整列宽
for col in ws.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2)
ws.column_dimensions[column].width = adjusted_width + 1 # 列宽+1
# 保存Excel文件
if not os.path.exists(excel_folder):
os.makedirs(excel_folder)
excel_file_path = os.path.join(excel_folder, excel_file)
wb.save(excel_file_path)
print(f'视频信息已保存到 {excel_file_path}')
代码说明
-
新增压缩率计算:在代码中增加了一个
compress变量,用于存储压缩率。计算方法为:compress = size / float(duration),其中size为文件大小,duration为视频时长。 -
将压缩率写入 Excel 文件:在代码中增加了一列,用于存储压缩率。使用
ws.cell(row=row, column=12, value=compress)将计算结果写入 Excel 文件的第 12 列。 -
更新表头:在代码中更新了表头,增加了
压缩率一列。 -
代码运行环境:该代码需要安装
openpyxl和mediainfo库。可以使用pip install openpyxl mediainfo命令进行安装。
代码运行方法
-
将代码保存为
.py文件,例如video_info.py。 -
在命令行中运行
python video_info.py。 -
按照提示输入要处理的视频文件夹路径。
-
代码会自动生成一个名为
video_info.xlsx的 Excel 文件,存储视频信息和压缩率。
注意事项
- 确保
mediainfo命令可以正常使用。 duration的单位为秒,size的单位为字节。- 压缩率的计算结果可能不完全准确,因为视频编码方式和视频内容都会影响压缩率。
通过以上修改,我们就可以轻松地计算视频文件的压缩率,并将其写入 Excel 文件,方便进行后续分析和比较。
希望这篇文章能够帮助您更好地理解和使用 Python3 代码来处理视频信息。如果您有任何疑问,请随时提出。
原文地址: https://www.cveoy.top/t/topic/mAGc 著作权归作者所有。请勿转载和采集!