Pythonic way to count occurrences from a list in a string

algorithm, python

Solution

This works!

def occurrence_counter(target_string):
    return sum(map(lambda x: x in string_list, target_string.split(' ')))

The string gets split into tokens, then each token gets transformed into a 1 if it is in the list, a 0 otherwise. The sum function, at last, sums those values.

EDIT: also:

def occurrence_counter(target_string):
    return len(list(filter(lambda x: x in string_list, target_string.split(' '))))

Problem

What's the best way to find the count of occurrences of strings from a list in a target string? Specifically, I have a list : ``` string_list = [ "foo", "bar", "baz" ] target_string = "foo bar baz bar" # Trying to write this function! count = occurrence_counter(target_string) # should return 4 ``` I'd like to optimize to minimize speed and memory usage, if that makes a difference. In terms of size, I would expect that `string_list` may end up containing several hundred substrings.

Original source

Related problems