How to find the most frequent word in a list of strings with Python

2 Answers

0 votes
def mostFrequentWord(words):
    frequency = 0
    size = len(words)
    frequent_word = ""
    i = 0
    
    for i in range(0, size, 1):
        count = 0
        for j in range(i + 1, size, 1):
            if words[j] == words[i]:
                count += 1
 
        if count >= frequency:
            frequent_word = words[i]
            frequency = count

    return frequent_word

lst = ["java", "c++", "c", "c#", "c", "go", "php", "java", "java", "c", "python", "php", "c"]

frequent_word = mostFrequentWord(lst)

print(frequent_word)



'''
run:

c

'''

 



answered Jan 1, 2024 by avibootz
0 votes
from collections import defaultdict

def mostFrequentWord(words):
    temp = defaultdict(int)
    size = len(words)
 
    for i in range(0, size, 1):
        temp[words[i]] += 1
 
    frequent_word = max(temp, key=temp.get)

    return frequent_word

lst = ["java", "c++", "c", "c#", "c", "go", "php", "java", "java", "c", "python", "php", "c"]

frequent_word = mostFrequentWord(lst)

print(frequent_word)



'''
run:

c

'''

 



answered Jan 1, 2024 by avibootz
...