合并百度影音的离线数据( with python 2.3)


Posted in Python onAugust 04, 2015

四种格式的解析:

filelist

slicelist

download.cfg

third_party_download.cfg

还是2个文件。替换之前版本即可。

初步测试正常,但时间轴不对。

代码如下:

# -*- coding: UTF-8 -*-
import os
import io
import codecs
import string
import shutil
import moviefmt
import traceback
def coroutine(func):
 def start(*args,**kwargs):
  g = func(*args,**kwargs)
  g.next()
  return g
 return start
@coroutine
def enum_movie_file(target): 
 selectedFolder = (yield)
 for fileitem in os.listdir(selectedFolder):    
  targetFO = os.path.join(selectedFolder,fileitem)  
  if(os.path.isfile(targetFO) == True):
   continue;  
  target.send(targetFO)  
@coroutine
def read_movie_file(funcDisp,target):
 while(True):
  filmFolder = (yield)
  for fileitem in os.listdir(filmFolder):  
   targetfile = os.path.join(filmFolder,fileitem)
   if(os.path.isfile(targetfile) == False):
    continue;   
   filebasename , fext = os.path.splitext(fileitem);    
   if(filebasename[0] == "."):
    continue   
   if(funcDisp.has_key(string.lower(fext))):
    pfn = funcDisp[string.lower(fext)];
    (targetFmt,targetObjects,filmFolderEx,filebasenameEx) = pfn(targetfile)
    if(targetFmt is None):
     continue;
    outputs = filmFolder,filebasename, (targetFmt,targetObjects,filmFolderEx,filebasenameEx);
    # outputs = filmFolder,filebasename, pfn(targetfile);
    target.send(outputs)
    break
def getWindowsText(orgText): 
 try:
  return orgText.encode('gbk') 
 except Exception as exc: 
  print("%s" % exc); 
  return orgText
@coroutine
def create_report(outputfile):
 objTar = codecs.open(outputfile,"w+")  
 while(1):
  filmFolder,filebasename,(extname,piece_list,filmFolderEx,filebasenameEx) = (yield)
  if(extname == None) :
   break;
  objTar.write('cd \"%s\"\r\n' % (filmFolderEx if filmFolderEx else filmFolder))  
  objTar.write('attrib -h *.*\r\n ')  
  if(len(piece_list) >1):
   objTar.write('copy /b ')  
  else:
   objTar.write('copy ')  
  if(len(piece_list) == 1):
   objTar.write('\"%s \"' %(getWindowsText(piece_list[0])))
  else:   
   bFirst = True
   for line in piece_list:
    if(bFirst == False):     
     objTar.write('+\"%s\"' %(getWindowsText(line))) 
    else:     
     objTar.write('\"%s\"' %(getWindowsText(line)))
     bFirst = False
  relpath = os.path.dirname(filmFolder)  
  currentPath = os.path.join(getWindowsText(relpath),getWindowsText(filebasenameEx if filebasenameEx else filebasename)) 
  objTar.write(' %s.%s\r\n' % (currentPath,extname))    
  objTar.write('cd %s\r\n' %(relpath))
 objTar.close()    
if __name__ == '__main__': 
 funcDisp = dict()
 funcDisp['.bdv_0000']= moviefmt.read_bdv_file;
 funcDisp['.rmvb_0000']= moviefmt.read_rmvb_file;
 funcDisp['.mkv_0000']= moviefmt.read_mkv_file;
 funcDisp['.bdv']= moviefmt.read_bdv_index;   
 funcDisp['.mp4_0000']= moviefmt.read_mp4_file;   
 funcDisp['']= moviefmt.read_mkv_2_file; 
 funcDisp['.filelist'] = moviefmt.read_filelist_index;
 funcDisp['.slicelist'] = moviefmt.read_slicelist_index;
 funcDisp['.cfg'] = moviefmt.read_cfg_index;
 try:
  rmf = enum_movie_file(read_movie_file(funcDisp,create_report('film.bat')))
  rmf.send(os.getcwd())
  rmf.close()
 except StopIteration:
  pass
 except Exception as exc: 
  print("%s" % exc); 
  info = traceback.format_exc()
  print(info)      
 print("done");  
# -*- coding: UTF-8 -*-
import os
import io
import sys
import string
import shutil
import codecs
import glob
import re
def read_bdv_index_V1(objFile):
 piece_list= list() 
 for line in objFile:
  if(line[0:4] != 'file'):
   continue;
  strings = string.split(line,'/')
  tarfile = strings[len(strings)-1]  
  tempText = string.strip(tarfile)
  piece_list.append(tempText)
 return "avi",piece_list,None,None
def read_bdv_index_V2(objFile):
 piece_list= list() 
 for line in objFile:  
  nPos = line.count('bdv')
  if( nPos <=0):
   continue;  
  tarfile = line[0:len(line)-2] 
  piece_list.append(tarfile) 
 return "mpeg",piece_list,None,None
def read_bdv_index_V3(objFile):
 piece_list= list()   
 oneFile= os.path.basename(objFile) 
 piece_list.append(oneFile)
 return "avi",piece_list,None,None
def read_bdv_index_V4(objFile):
 piece_list= list() 
 #skip #EXT-X-MEDIA-SEQUENCE
 objFile.readline();
 for line in objFile:
  if(line.startswith('#')==True):
   continue;  
  piece_list.append(line.replace('\r\n',''))
 return "avi",piece_list,None,None
def count_file_item(objFile,extText):
 cItem = 0;
 folderName = os.path.dirname(objFile)
 for fileitem in os.listdir(folderName): 
  filebasename , fext = os.path.splitext(fileitem); 
  if(fext == extText):
   cItem = cItem +1
 return cItem 
def read_bdv_index(filename):
 piece_list= list() 
 ext_type = None
 filmFolderEx = None
 filebasenameEx = None
 # total file count
 cItem = count_file_item(filename,".bdv")
 if(cItem == 1):
  ext_type,piece_list,filmFolderEx,filebasenameEx = read_bdv_index_V3(filename)
 else:
  objFile = codecs.open(filename,'r','utf-8') 
  topline = objFile.readline();
  bdv_ver = topline.replace("\r\n","")
  if(bdv_ver == '#EXTM3U'):
   v3Text = objFile.readline();
   if(v3Text.startswith('#EXT-X-TARGETDURATION') == False):
    ext_type,piece_list = read_bdv_index_V2(objFile)
   else:
    ext_type,piece_list = read_bdv_index_V4(objFile)
  else:
   ext_type,piece_list = read_bdv_index_V1(objFile)
  objFile.close()  
 return (ext_type ,piece_list,filmFolderEx,filebasenameEx)  
def read_bdv_file(filename):
 piece_list= list()
 piece_list.append('*.bdv_*')
 return ('avi',piece_list,None,None)
def read_rmvb_file(filename):
 piece_list= list()
 piece_list.append('*.rmvb_*')
 return ('rmvb',piece_list,None,None)
def read_mkv_file(filename):
 piece_list= list() 
 piece_list.append('*.mkv_*')
 return ('mkv',piece_list,None,None)
def read_mp4_file(filename):
 piece_list= list() 
 piece_list.append('*.mp4_*')
 return ('mp4',piece_list,None,None)
def read_mkv_2_file(filename):
 piece_list= list() 
 piece_list.append('video_*')
 return ('mkv',piece_list,None,None)
def read_filelist_index(filename):
 filmFolderEx = None
 filebasenameEx = None
 objFile = codecs.open(filename,'r','utf-8') 
 topline = objFile.readline();
 bdv_ver = topline.replace("\r\n","")
 if(bdv_ver == '#EXTM3U'):
  v3Text = objFile.readline();
  if(v3Text.startswith('#EXT-X-TARGETDURATION') == False):
   ext_type,piece_list,filmFolderEx,filebasenameEx = read_bdv_index_V2(objFile)
  else:
   ext_type,piece_list,filmFolderEx,filebasenameEx = read_bdv_index_V4(objFile)   
 else:
  ext_type,piece_list,filmFolderEx,filebasenameEx = read_bdv_index_V1(objFile)
 objFile.close()  
 return ("mp4" ,piece_list,filmFolderEx,filebasenameEx)    
def read_slicelist_index(filename):
 piece_list= list() 
 objFile = codecs.open(filename,'r','utf-8') 
 topline = objFile.readline();
 bdv_ver = topline.replace("\r\n","")
 if(bdv_ver == '#BD-SECTION'): 
  while(True):
   currentLine = objFile.readline();
   if(currentLine is None or len(currentLine) ==0):
    break
   piece_list.append(currentLine.replace("\r\n",""))
 objFile.close()  
 return ('mp4',piece_list,None,None)
def read_cfg_index(filename):
 piece_list= list() 
 simpleFileName = os.path.basename(filename)
 if(simpleFileName == 'download.cfg'):
  simpleFolderName = os.path.dirname(filename)
  chkLst =glob.glob(os.path.join(simpleFolderName, '*.filelist'));
  if(chkLst is not None and len(chkLst) >0):
   return (None,None,None,None)
  chkLst =glob.glob(os.path.join(simpleFolderName, '*.bdv'));
  piece_list.append(chkLst[0]);
  return ('avi',piece_list)
 if(simpleFileName != 'third_party_download.cfg'):
  raise Exception('unknown format file : %s' %(filename))
 reObj = re.compile('(?P<var_key>\S+):(?P<var_value>\S+)',re.IGNORECASE)
 lineDict = dict()
# [orgLines.append(orgLine.replace("\r\n","") ) for orgLine in codecs.open(filename,'r','utf-8')]
 for orgLine in codecs.open(filename,'r','utf-8'):
  orgLine = orgLine.replace("\r\n","")  
  results = reObj.findall(orgLine)
  if(len(results) > 0):
   lineDict[results[0][0]] =results[0][1]
 resID = lineDict["resource"] 
 vid = lineDict[ '%s_vid'%(resID)]
 targetName = lineDict["video_name"]
 simpleFolderName = os.path.dirname(filename)
 upLevelFolderName = os.path.dirname(simpleFolderName)
 targetFolder = os.path.join(upLevelFolderName,vid)
 targetFolder = os.path.join(targetFolder,vid)
 chkLst =glob.glob(os.path.join(targetFolder, '*.%s*' %(resID)));
 targetFile = chkLst[0] 
  #skip #EXT-X-MEDIA-SEQUENCE 
 for line in codecs.open(targetFile,'r','utf-8'):
  if(line.startswith('#')==True):
   continue;  
  line = os.path.basename(line.replace('\r\n',''))
  line = os.path.basename(line.replace('\r',''))
  line = os.path.basename(line.replace('\n',''))
  piece_list.append(line )
 return ('avi',piece_list,targetFolder,targetName)

以上就是本文的全部内容,希望大家喜欢。

Python 相关文章推荐
python抓取豆瓣图片并自动保存示例学习
Jan 10 Python
Python正则抓取新闻标题和链接的方法示例
Apr 24 Python
Python爬取附近餐馆信息代码示例
Dec 09 Python
对python 合并 累加两个dict的实例详解
Jan 21 Python
python使用原始套接字发送二层包(链路层帧)的方法
Jul 22 Python
浅析python 中大括号中括号小括号的区分
Jul 29 Python
PyTorch: 梯度下降及反向传播的实例详解
Aug 20 Python
解决pandas展示数据输出时列名不能对齐的问题
Nov 18 Python
python 实现检验33品种数据是否是正态分布
Dec 09 Python
django框架ModelForm组件用法详解
Dec 11 Python
解析PyCharm Python运行权限问题
Jan 08 Python
Python操作word文档插入图片和表格的实例演示
Oct 25 Python
python利用datetime模块计算时间差
Aug 04 #Python
使用python加密自己的密码
Aug 04 #Python
Python实现字典的key和values的交换
Aug 04 #Python
python利用装饰器进行运算的实例分析
Aug 04 #Python
浅谈python多线程和队列管理shell程序
Aug 04 #Python
python中使用序列的方法
Aug 03 #Python
python实现备份目录的方法
Aug 03 #Python
You might like
优化php效率,提高php性能的一些方法
2011/03/24 PHP
php随机显示图片的简单示例
2014/02/15 PHP
PHP中批量生成静态html(命令行下运行PHP)
2014/04/19 PHP
php无序树实现方法
2015/07/28 PHP
php 自定义错误日志实例详解
2016/11/12 PHP
利用laravel+ajax实现文件上传功能方法示例
2017/08/13 PHP
TP3.2.3框架使用CKeditor编辑器在页面中上传图片的方法分析
2019/12/31 PHP
js cookies 常见网页木马挂马代码 24小时只加载一次
2009/04/13 Javascript
写出更好的JavaScript之undefined篇(上)
2009/11/22 Javascript
jquery.post用法示例代码
2014/01/03 Javascript
ui组件之input多选下拉实现方法(带有搜索功能)
2016/07/14 Javascript
简单的JS轮播图代码
2016/07/18 Javascript
很棒的js Tab选项卡切换效果
2016/08/30 Javascript
vue组件发布到npm简单步骤
2017/11/30 Javascript
JS判断用户用的哪个浏览器实例详解
2018/10/09 Javascript
ajax与jsonp的区别及用法
2018/10/16 Javascript
详解JavaScript 新语法之Class 的私有属性与私有方法
2019/04/23 Javascript
Openlayers实现点闪烁扩散效果
2020/09/24 Javascript
node.js文件的复制、创建文件夹等相关操作
2021/02/05 Javascript
[49:08]完美世界DOTA2联赛PWL S2 LBZS vs FTD.C 第一场 11.27
2020/12/01 DOTA
python如何实现excel数据添加到mongodb
2015/07/30 Python
用Python编写简单的微博爬虫
2016/03/04 Python
python判断字符串编码的简单实现方法(使用chardet)
2016/07/01 Python
机器学习python实战之决策树
2017/11/01 Python
Django框架使用富文本编辑器Uedit的方法分析
2018/07/31 Python
PyQt5 在label显示的图片中绘制矩形的方法
2019/06/17 Python
Python跑循环时内存泄露的解决方法
2020/01/13 Python
python利用opencv保存、播放视频
2020/11/02 Python
HTML5中如何显示视频呢 HTML5视频播放demo
2013/06/08 HTML / CSS
什么是会话Bean
2015/05/14 面试题
经济贸易专业自荐信
2014/06/11 职场文书
三严三实对照检查材料范文
2014/09/23 职场文书
Python基础之Socket通信原理
2021/04/22 Python
关于vue中如何监听数组变化
2021/04/28 Vue.js
JDBC连接的六步实例代码(与mysql连接)
2021/05/12 MySQL
Python中的socket网络模块介绍
2022/07/23 Python