Regex and text data noob here.
I have a list of terms and I want to get a single sum of the total times the strings from my list appear in a separate string. In the example below, the letter "o" appears 3 times in my string and the letter "b" appears 2 times. I've created a variable called allcount which I know doesn't work, but ideally would have a total sum of 5.
Any help is appreciated.
import re
mylist = ['o', 'b']
my_string = 'Bob is cool'
onecount = len(re.findall('o', my_string)) #this works
#allcount = sum(len(re.findall(mylist, my_string))) #this doesn't work
CodePudding user response:
Building a Counter
and iterating over the list elements would be easier and more efficient:
from collections import Counter
c = Counter(my_string.lower())
# Counter({'b': 2, 'o': 3, ' ': 2, 'i': 1, 's': 1, 'c': 1, 'l': 1})
[c[s] for s in mylist]
# [3, 2]
CodePudding user response:
You have to find different patterns in your string.
This can be done by using pipe | sign
import re
mylist = ['o', 'b']
my_string = 'Bob is cool'
onecount = len(re.findall("o|b|B", my_string)) #this works
print(onecount)