count number of words occurrence in text based on list of string
Question:
I want to know what is the best approach to find the number of occurrence in text based on list of string. I found some use sum(any()) but it didn’t work because if text contains "re" it will count it
list1 = ['red', 'green', 'amazing', 'orange', 'amazing color', 'gray', 'pink']
text="green and red is an amazing color "
The expect count is 4
Thank you
Answers:
Probably there is a much smoother way, but the simple for-loop does the job.
list1 = ['red', 'green', 'amazing', 'orange', 'amazing color', 'gray', 'pink']
text="green and red is an amazing color "
amount_words_from_list_in_text = 0
for word in list1:
if word in text:
amount_words_from_list_in_text += 1
print(amount_words_from_list_in_text)
All you need to do is use the built-in sum()
function along with str.count()
and a generator expression:
sum(text.count(item) for item in list1)
I want to know what is the best approach to find the number of occurrence in text based on list of string. I found some use sum(any()) but it didn’t work because if text contains "re" it will count it
list1 = ['red', 'green', 'amazing', 'orange', 'amazing color', 'gray', 'pink']
text="green and red is an amazing color "
The expect count is 4
Thank you
Probably there is a much smoother way, but the simple for-loop does the job.
list1 = ['red', 'green', 'amazing', 'orange', 'amazing color', 'gray', 'pink']
text="green and red is an amazing color "
amount_words_from_list_in_text = 0
for word in list1:
if word in text:
amount_words_from_list_in_text += 1
print(amount_words_from_list_in_text)
All you need to do is use the built-in sum()
function along with str.count()
and a generator expression:
sum(text.count(item) for item in list1)