Home > Blockchain >  How to calculate the number of matching string with external dictionary in Python
How to calculate the number of matching string with external dictionary in Python

Time:05-28

I've created a dictionary using other source and I'm trying to count the number of matching word and the non-matching word of a sentence.

dictionary = ["hello", "good", "happy"]
str1 = ["the dog is happy"]

For example above, I want to find out the number of word in str1 that is matching with the dictionary and the number of non-matching, the result would be something like number of matching = 1 and number of non-matching = 3. Is this possible?

CodePudding user response:

d = ["hello", "good", "happy"]
s = "the dog is happy"

note: i turned ["the dog is happy"] --> "the dog is happy" as the list is unnecessary

l = [i in d for i in s.split(' ')]
matching = l.count(True)  # can also use sum(l)
non_matching = l.count(False)
  • Related