首页 > 解决方案 > Python - 拆分、正则表达式和条件

问题描述

我有一个目标艺术家,想获取其通讯员 ID,如下所示:

import re
target = 'Portishead'
videos = ['Portishead - Roads (Vg1jyL3cr60)', 'Portishead - Roads - (WQYsGWh_vpE)', 'Need For Speed (Linkin Park - Roads Untraveled) Music Video (7Lkq7bf6kU8)', 'Lawson - Roads (I-SOaSU0ieA)', 'Vargas & Lagola - Roads (Audio) (Kd3s20GmPVE)']

for item in videos:
    artist = item.split('-')[0]
    # here I get whats inside parenthesis, not always an id
    video_id = re.findall('\(([^)]+)', item)
    # and here the id, which is always the last split item
    id_ = (video_id[-1])
    if artist == target:
       print id_

但我的if情况不适用于目标艺术家。我没有打印任何结果。

for考虑到实际列表非常大,使用循环或其他方式实现此目的的最佳方法是什么?

我想获取高于“Vg1jyL3cr60”


编辑:@Alexandre Cécile。我在这里发布了调用 youtube API 的整个函数,如果你有兴趣完善缩小艺术家视频搜索范围的功能,一旦你传递了曲目标题和艺术家姓名。不过,您将需要一把钥匙。

from google.oauth2 import service_account


def youtube_id(track_name, target_artist):

    GET_CREDENTIALS = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')
    PASS_CREDENTIALS = 
    service_account.Credentials.from_service_account_file(GET_CREDENTIALS)
    YOUTUBE_API_SERVICE_NAME = "youtube"
    YOUTUBE_API_VERSION = "v3"
    DEVELOPER_KEY = "mykey"

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, credentials=PASS_CREDENTIALS,
    developerKey=None)
    # Call the search.list method to retrieve results matching the specified
    # query term.
    search_response = youtube.search().list(
    q=track_name,
    part="id,snippet",
    #maxResults=track_name.max_results
    ).execute()

    videos = []
    videos_ids = []
    channels = []
    playlists = []

    # Add each result to the appropriate list, and then display the lists of
    # matching videos, channels, and playlists.
    for search_result in search_response.get("items", []):
        if search_result["id"]["kind"] == "youtube#video":
            videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                 search_result["id"]["videoId"]))
            videos_ids.append("%s" % (search_result["id"]["videoId"]))
        elif search_result["id"]["kind"] == "youtube#channel":
            channels.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["channelId"]))
        elif search_result["id"]["kind"] == "youtube#playlist":
            playlists.append("%s (%s)" % (search_result["snippet"]["title"],
                                    search_result["id"]["playlistId"]))

    print ("Videos:\n", "\n".join(videos), "\n")
    print ("Channels:\n", "\n".join(channels), "\n")
    print ("Playlists:\n", "\n".join(playlists), "\n")

    ids=[]
    for video in videos:
        artist = re.split(r'\s*-\s*', video)[0]
        id = re.search(r'.*\(([^)]+)', video)[1]
        if id and artist == target_artist:
            videos_ids.append(id)
            print ('VIDEOS IDS',  videos_ids)

    return videos_ids[-1] 

标签: pythonregexstringif-statementyoutube-api

解决方案


当您将艺术家与曲目分开时,您将在'-'. 如果您查看实际的字符串,您会看到连字符周围有空格,这将包含在拆分结果中。

解决方案是对.strip()变量artist去掉空格。


推荐阅读