Kendel Ventonda
Kendel Ventonda

Reputation: 411

Python: Getting specific list elements

So I made a list of elements from a HTML-Page and counted the frequency of these elements. But I just need some specific elements like "bb" and "nw". So I don't know what position they'll have in the list and I'm not sure how to seperate them from the other elements.

This is my code so far:

from bs4 import BeautifulSoup
import urllib2
import re
import operator
from collections import Counter
from string import punctuation

source_code = urllib2.urlopen('https://de.wikipedia.org/wiki/Liste_von_Angriffen_auf_Fl%C3%BCchtlinge_und_Fl%C3%BCchtlingsunterk%C3%BCnfte_in_Deutschland/bis_2014')
html = source_code.read()
soup = BeautifulSoup(html, "html.parser")

text = (''.join(s.findAll(text=True))for s in soup.findAll('a'))

c = Counter((x.rstrip(punctuation).lower() for y in text for x in y.split()))

bb,nw=operator.itemgetter(1,2)(c.most_common())
print(bb,nw)

Thank you for your help and any hints.

Upvotes: 0

Views: 52

Answers (1)

user2390182
user2390182

Reputation: 73450

You could use a filter:

relevant_items = ('bb', 'nw')
items = filter(lambda x: x[0] in relevant_items, c.most_common())

Alternatively, you can already filter in the comprehension:

c = Counter((x.rstrip(punctuation).lower() for y in text for x in y.split() if x in relevant_items))

Upvotes: 2

Related Questions