-1

I am trying to achieve this

string_list = ["red","blue","green"]
text = "This is a string about my favourite colours like red blue and green but blue is the best"
some_function(string_list,text)

Output: [1,2,1]

How do I achieve this? Getting a number which adds all occurrences (4 in this case) is no problem, but I´d like it to be seperated by the string_list items.

Justin
  • 63
  • 5
  • Can you write code to count the occurrences of `red`? of `blue`? of `green`? If you put these things together, why does it not solve the problem? Also, why is this tagged `pandas` - why would the Pandas library be relevant here? – Karl Knechtel Jan 14 '23 at 15:35

3 Answers3

3
return [text.count(string) for string in string_list]
WingedSeal
  • 439
  • 1
  • 4
  • 12
1

You may use count() function to count a substring in a string. Below code may help

def get_count(slist,text):
    result=[]
    for string in slist:
        result.append(text.count(string))
    return result
    

string_list = ["red","blue","green"]
text = "This is a string about my favourite colours like red blue and green but blue is the best"

print(get_count(string_list,text))

Output

[1, 2, 1]
0

Here's a long way of doing it:

from collections import defaultdict

string_list = ["red","blue","green"]
text = "This is a string about my favourite colours like red blue and green but blue is the best"


def count_occurrences(string_list, text):
    counts = defaultdict(int)
    for string in text.split():
        if string in string_list:
            counts[string] += 1
    return counts.values()

print(count_occurrences(string_list, text))

dict_values([1, 2, 1])
NYC Coder
  • 7,424
  • 2
  • 11
  • 24