Two unlinked lists, finding position of item in one and printing the positions from the other

Viewed 51

So I was given an assignment to webscrape off a website. I have two lists, one containing quotes and the other of who said the quotes. I was told to print the quotes Albert Einstein said. So I have code to find the positions of when Albert Einstein comes up in the first list and I've been trying to print off the quotes in the same positions as when Albert Einstein comes up. I've been stuck on this for two days now and it's to be handed in later, please help :)

error message - StopIteration

import requests 
import bs4

res = requests.get("http://quotes.toscrape.com/") 

soup = bs4.BeautifulSoup(res.text,'lxml') 
all_author = []
all_quote = []
for element in soup.select('small'):
    all_author.append(element.text)
for element in soup.select('span'):
    all_quote.append(element.text) 


g = (i for i, n in enumerate(all_author) if n == 'ALbert Einstein')

for x in all_quote:
    print (all_quote.index(next(g)))

2 Answers

You can directly use the list comprehension to get all the indices and then print the quotes according to each index:

g = [i for i, n in enumerate(all_author) if n == 'Albert Einstein']
for i in g:
    print(all_quote[i])

However there are unwanted strings in all_quote such that, len(all_author)!=len(all_quote). You can filter the elements when filling the list e.g.:

all_quote = []
for element in soup.select('span'):
    t = element.text
    if t[0] == '“' and t[-1] == '”':
        all_quote.append(t)

You can use list comprehension to find out the position of the author and then use that position to pick the quotes from quotes list

quotes = ['hope', 'faith', 'welcome']
author = ['einstein','tesla','einstein']
indices = [ i for i, x in enumerate(author) if x == 'einstein']
author_quote = [ quotes[index] for index in indices]
Related