SoloTriesToLearn
SoloTriesToLearn

Reputation: 39

Counting Occurences of a String within elements of a list?

I'm trying to count the amount of times "a class" occurs within each "h2 class", so I split the parsed texted by "h2 class" but am having struggles with the second part, this is where I'm at

#splitting parsed text by header
parsed.split("h2 class")

#creating the list for the a value count to be stored
aValCount = []

#counting amount of items per header
for i in range (len(parsed)):
    aValCount = aValCount + ((parsed[i]).count("a class"))

the error I'm getting is

TypeError: can only concatenate list (not "int") to list

, but I can't figure out how to this without getting some sort of error

Edited: Thought I should add, I want it to be a list of the counts from the strings, so the count from element one in parsed, should be element 1 in aValCount

Upvotes: 1

Views: 51

Answers (1)

Alpha Beta Charlie
Alpha Beta Charlie

Reputation: 841

The issue is that aValCount is an array and ((parsed[i]).count("a class")) is an int.

What you want is to add the count to aValCount so you need to pass another array.

aValCount = aValCount + [((parsed[i]).count("a class"))]

If you add [...] that should do it. Or you can also do

aValCount.append(((parsed[i]).count("a class"))])

Hope that help.

results = parsed.split("h2 class")
aValCountList = []

for i in range (len(results)):
    aValCountList.append((results[i]).count("a class"))

Upvotes: 1

Related Questions