Skip to content Skip to sidebar Skip to footer

How To Return The Count Of Words From A List Of Words That Appear In A List Of Lists?

I have a very large list of strings like this: list_strings = ['storm', 'squall', 'overcloud',...,'cloud_up', 'cloud_over', 'plague', 'blight', 'fog_up', 'haze'] and a very large

Solution 1:

You can use sum function within a list comprehension :

[sum(1for i in list_strings if i insub[0]) forsubin lis_of_lis]

Solution 2:

result= []
for sentence in lis_of_lis:
    result.append(0)
    for word in list_strings:
        if word in sentence[0]:
            result[-1]+=1
print(result)

which is the long version of

result = [sum(1 for word in list_strings if word in sentence[0])  for sentence in lis_of_lis]

This will return [2,2,1] for your example.

If you want only whole words, add spaces before and after the words / sentences:

result= []
for sentence in lis_of_lis:
    result.append(0)
    for word in list_strings:
        if ' '+word+' 'in' '+sentence[0]+' ':
            result[-1]+=1
print(result)

or short version:

result = [sum(1 for word in list_strings if ' '+word+' ' in ' '+sentence[0]+' ')  for sentence in lis_of_lis]

This will return [2,1,1] for your example.

Solution 3:

This creates a dictionary with the words in list_string as keys, and the values starting at 0. It then iterates through the lis_of_lis, splits the phrase up into a list of words, iterates through that, and checks to see if they are in the dictionary. If they are, 1 is added to the corresponding value.

word_count=dict()for word in list_string:word_count[word]=0for phrase in lis_of_lis:words_in_phrase=phrase.split()for word in words_in_phrase:if word in word_count:word_count[word]+=1

This will create a dictionary with the words as keys, and the frequency as values. I'll leave it to you to get the correct output out of that data structure.

Post a Comment for "How To Return The Count Of Words From A List Of Words That Appear In A List Of Lists?"