【问题标题】:Python, sorting extracted youtube dataPython,对提取的 youtube 数据进行排序
【发布时间】:2021-09-19 19:21:22
【问题描述】:

我正在尝试检索 youtube 频道中观看次数最多的 10 个视频。我不太确定该怎么做,我相信结果会返回 10 个特定时间范围内的视频。此外,绘制的条形图中的 y 轴('views')不按顺序排列。总之,我需要帮助绘制与每个视频相关的观看次数图表(len(10))

获取统计数据

youtube = build('youtube', 'v3', developerKey=api_key)

request = youtube.channels().list(
        part='statistics',
        id='UC-lHJZR3Gqxt24_Td_AJ5Yw'
        )

#To get a response, use execute()
response = request.execute()

#List indices must be intergers or slices, not str
stats = response['items'][0]['statistics']
video_count = stats['videoCount']

contentdata = youtube.channels().list(
    id='UC-lHJZR3Gqxm24_Vd_AJ5Yw',
    part='contentDetails'
    ).execute()

playlist_id = contentdata['items'][0]['contentDetails']['relatedPlaylists']['uploads']
videos = []
next_page_token = None

while 1:
    res = youtube.playlistItems().list(
        playlistId=playlist_id,
        part='snippet',
        maxResults=50,
        pageToken=next_page_token
        ).execute()

    videos += res['items']
    next_page_token = res.get('nextPageToken')

    if next_page_token is None:
        break

#Get video ID for each video
video_ids = list(map(lambda x:x['snippet']['resourceId']['videoId'], videos))

#Get statistics for each video
stats = []
for i in range(0, len(video_ids), 40):
    res = youtube.videos().list(
        id=','.join(video_ids[i:i+40]), 
        part='statistics'
        ).execute()
    stats+=res['items']

views, links = [], []

for i in range(len(videos[:10])):
    try:
        title = (videos[i]['snippet']['title'])
        view = (stats[i]['statistics']['viewCount'])
        link = f"<a href='{stats[i]['id']}'>{title}</a" 

    except KeyError:
        continue

    else:
        views.append(view)
        links.append(link)

绘图

from youtube_bar import links, views
from plotly.graph_objs import Bar
from plotly import offline

#Create bar graph with data
data = [{
    'type': 'bar',
    'x': links,
    'y': views,
    'opacity': 0.6,
    'marker': {
        'color': 'rgb(150, 100, 20)',
        'line': {'width':1.5, 'color': 'rgb(25, 25, 25)'}
    },
}]

my_layout = {
    'title': 'Top 10 most views for channel',
    'titlefont': {'size':28},
    'xaxis': {
        'title': 'Videos',
        'titlefont': {'size': 24},
        'tickfont': {'size': 14},
        },
    'yaxis': {
        'title': 'Views',
        'titlefont': {'size': 24},
        'tickfont': {'size': 14},
    },
}

fig = {'data': data, 'layout': my_layout}

offline.plot(fig, filename='youtube_videos.html')

图表

【问题讨论】:

    标签: python api youtube plotly


    【解决方案1】:

    代码中的循环:

    for i in range(len(videos[:10])):
    

    只拍摄从 1 到 10 的视频(最近,这就是“时间范围”的原因),您必须在此之前根据它的 viewCount 对可变视频进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2016-01-01
      • 1970-01-01
      • 2012-07-11
      • 2019-05-05
      • 2017-04-19
      • 2021-10-15
      相关资源
      最近更新 更多