我试图构建一个youtube视频ID图,考虑到在每个步骤中恢复的建议数(我们称之为numberOfRelated)和图的最大深度(maxDepth)是固定的。(见附件中的图解说明)
http://postimg.org/image/ytp80f02n/
我使用的是YouTube数据api(v3),执行时间比较困难(如果numberOfRelated=10和maxDepth=3,执行时间大约是2分钟)
# -*- coding: utf-8 -*-
from lib import function as f
import urllib
import json
import sys
import argparse
import logging
api_key = 'API_KEY'
videosId = []
maxDepth=2
numberOfRelated = 5
# FIND RELATED VIDEOS FROM A SPECIFIC ONE
def getVideoRelated (depth, VideoID):
related_video_api ="https://www.googleapis.com/youtube/v3/search?relatedToVideoId="+str(VideoID)+"&type=video&maxResults="+str(numberOfRelated)+"&key="+str(api_key)+"&part=id"
try:
inp = urllib.urlopen(related_video_api)
respRelated=json.load(inp)
inp.close()
# list of related video from a specific one
for x in xrange(0,len(respRelated['items'])):
videosId.append([depth,respRelated['items'][x]['id']['videoId']])
except Exception, err:
print "error when trying to get the ID of related videos"
def getAllID(ID, depth):
if (depth==maxDepth):
return
depth+=1
getVideoRelated(depth,ID)
BORNINF,BORNSUP = maxDepth*(depth-1), maxDepth*depth
for x in xrange(BORNINF,BORNSUP):
getAllID(videosId[x][1],depth)
def main():
url='https://www.youtube.com/watch?v=2HIuN5lxMCI'
initialID = f.get_id(url)
videosId.append([0,initialID])
getAllID(initialID,0)
print videosId
print len(videosId)
if __name__ == '__main__':
main()
你知道如何更有效地做到这一点吗? (例如:在死在我的电脑前恢复numberOfRelated=50和maxDepth=5的数据)
我的代码似乎也无法恢复我想要的所有ID。我想它来自于代码的这一部分,因为我搞不懂这个问题
BORNINF,BORNSUP = maxDepth*(depth-1), maxDepth*depth
for x in xrange(BORNINF,BORNSUP):
getAllID(videosId[x][1],depth)
谢谢你的帮助!你知道吗
经过几个晚上的努力,我终于找到了一个令人满意的解决办法。你知道吗
递归函数:
用第一个“节点”(aka video)实例化递归函数
它仍然很慢,但我可以让它工作:
如果maxDepth=5和numberOfRelated=5,我得到32,1 如果maxDepth=6和numberOfRelated=5,我得到了156s
值得一提的是,这里提供了全局解决方案(从ID图恢复数据):https://github.com/kwnovi/melihat/blob/master/main.py
相关问题 更多 >
编程相关推荐