-6

I have a string for instance

message = "The quick brown fox jumps over the lazy dog"

and a large list of words. I would like to get the count (int) of how many times those words occur in string. If list is

words = ["the","over","azy","dog"]

It would return 4 (not 5). It shouldn't count word "the" 2 times. Each word only once!

P_95
  • 145
  • 8

2 Answers2

1
len(set(message.split()) & set(words))
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

If you want to check for substrings also i.e azy in lazy, you need to check each word from words is in each substring of message:

message = "The quick brown fox jumps over the lazy dog"

words = ["the","over","azy","dog"]
print(sum(s in word for word in set(message.lower().split()) for s in words))
4

Or simply check if each word from words is contained in the string:

print(sum(word in message for word in words))
4

You also need to call lower on the string if you want to ignore case.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321