从字典列表(或生成器)中提取字符串

Extracting string from lists of dictionaries (or generator)

我正在使用 scrapetube to get the video IDs of all the videos from a YouTube channel. The scrape code returns a generator object which I have converted to a list of dictionaries containting other dictionaries, lists and string. The scraping code works, but here still some sample data. I am only interested in the string video Id --> see picture for illustration purposes

抓取数据

如何遍历字符串 videoId 中的所有视频 ID 并将它们保存在新变量(列表或数据帧)中以供进一步处理?

import scrapetube

vid = scrapetube.get_channel('UC_zxivooFdvF4uuBosUnJxQ')
type(vid) #generator file 
video = next(vid) #extract values from generator & then convert it
videoL = list(vid) #convert it to a list

#code not working
for item in videoL['videoId']:
    entry = {}
    videoId = item['videoId']
    for i in range(len(videoId)):
        entry.append(int(videoId[i][0:10]))

#error message: TypeError: list indices must be integers or slices, not str

我使用了 中的代码片段,但似乎无法正常工作。

知道术语会很有帮助,所以让我们逐步了解它。

什么是发电机?

生成器,顾名思义,按需生成值。 它们在这种情况下的用处是,如果您不想将所有数据都存储在内存中,您一次只能迭代一个生成的值,并且只提取您需要的内容。

考虑一下:

def gen_one_million():
    for i in range(0, 1_000_000):
        yield i

for i in gen_one_million():
    # do something with i

与其在 list 或内存中的某个容器中拥有一百万个元素,不如一次只获取一个。如果你想把它们全部放在 list 中,用 list(gen_one_million()) 很容易做到,但如果你不需要它们,你不必将它们全部放在内存中。

什么是 list 以及如何使用它们?

python中的一个list是用括号[]表示的容器。要访问 list 中的元素,您可以对其进行索引 i = my_list[0] 或对其进行迭代。

for i in my_list:
    # do something with i

什么是 dict 以及如何使用它们?

A dict 是一个 python key/value 容器类型,由大括号和键和值之间的冒号表示。 {key: value} 要访问 dict 中的值,您可以引用您想要 i = my_dict[key] 值的键,其中 key 是字符串或整数或其他一些可哈希类型。您也可以对其进行迭代。

for key in my_dict:
    # do something with the key

for value in my_dict.values():
    # do something with the key

for key, value in my_dict.items():
    # do something with the key and value

我的案例如何适应这一切?

查看您的示例数据,您似乎已经将其从生成器转换为 list

[
    {
        'videoId': '8vCvSmAIv1s', 
        'thumbnail': {
            'thumbnails': [
                {
                    'url': 'https://i.ytimg.com/vi/8vCvSmAIv1s/hqdefault.jpg?sqp=-oaymwEbCKgBEF5IVfKriqkDDggBFQAAiEIYAXABwAEG&rs=AOn4CLDn3-yb8BvctGrMxqabxa_nH-UYzQ',
                    'width': 168, 
                    'height': 94}, # etc..
                }
            ]
        }  
    }
]      

但是,由于您只需要遍历它并访问每个生成的 dict 中的 'videoID' 键,因此没有理由进行转换。 只需直接遍历生成器并访问每个生成的密钥 dict.

video_ids = []
for item in vid:
    video_ids.append(item['videoId'])

或者更好,作为 list 理解。

video_ids = [item['videoId'] for item in vid]