Home > Software engineering >  Count the frequency of a list of words within another list
Count the frequency of a list of words within another list

Time:04-22

I have a list of lists which I want to see the frequency in a sentence:

words = [plates, will]
sentence = [the, plates, will, still, shift, and, the, clouds, will, still, spew,]

I want to count how many times a set of word has been mentioned in a list. So from the list words [plates,will] is mentioned just 1 time in the sentence

I have a whole column which I want to iterate.

Desirable output is:

sentence word frequency
[the, plates, will, still, shift, and, the, clouds, will, still, spew,] [plates ,will] 1
[the, plates, will, still, shift, and, the, clouds, will, still, spew,] [still, spew] 1

I have tried this:

for word in word:
    if word in sentence:
        counts[word]  = 1
    else:
        counts[word] = 1

also

[[word.count() for word in b if word in row] for row in b]

Any help for the right output?

CodePudding user response:

This is not inline but it does the job I understood you asked for.

words = ["plates", "will"]
sentence = ["the", "plates", "will", "still", "shift", "and"]

count = 0
# Go through each word in the sentence
for si in range(len(sentence) - len(words)):
    match = True
    # Compare if the following words match
    for wi, word in enumerate(words):
        # Break if one word is wrong
        if sentence[si   wi] != word:
            match = False
            break
    if match:
        count  =1
print(count)

CodePudding user response:

I think that soultion with Counter is simplier.

from collections import Counter

words = ['plates', 'will']
sentence = ['the', 'plates', 'will', 'still', 'shift', 'and', 'the', 'clouds', 'will', 'still', 'spew',]

word_counts = Counter(sentence)

for word in words:
    print(word, word_counts[word])
  • Related