0

Hope you all are fine i am trying to Find the word that appears most frequently in that string and the total number of times that word appears in that string i have managed to find the word but having trouble with counting it and returning it

from statistics import mode
test_list ="a cat in a hat and a big black bear on a big black rug"
print("The original list is : " + str(test_list))
temp = [wrd for sub in test_list for wrd in sub.split()]
res = mode(temp)
print("Word with maximum frequency : " + str(res))

SO i want to have output same as this one Expected output

please help me and thanks in advance

Ahtesham Khan
  • 69
  • 1
  • 6
  • Please see my [answer](https://stackoverflow.com/questions/70133642/how-to-find-the-word-that-appears-most-frequently-in-that-string-and-the-total-n/70133710#70133710) – Pranava Mohan Nov 27 '21 at 09:58

3 Answers3

0

This is easily solved using collections.Counter:

from collections import Counter
counter = Counter(test_list.split())
print(counter.most_common(1))
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
0

You can use the built-in collections.Counter:

from collections import Counter

test_list ="a cat in a hat and a big black bear on a big black rug"
print(f"The original list is : {test_list}")  # Prefer f-strings if your python version has support for it
count = Counter(test_list.split())
print(count.most_common(1))  # Note that this will only give one return value, even if there's a tie
frippe
  • 1,329
  • 1
  • 8
  • 15
0

There you go:

test_list ="a cat in a hat and a big black bear on a big black rug big big big big"

word_list = test_list.split(' ')

def most_frequent(List):
    counter = 0
    elem = List[0]
     
    for i in List:
        curr_frequency = List.count(i)
        if(curr_frequency> counter):
            counter = curr_frequency
            elem = i
 
    return elem, counter
    
mostFrequentItem, totalNumberOfTimes = most_frequent(word_list)
Pranava Mohan
  • 533
  • 2
  • 8
  • 18