简体   繁体   中英

Finding highest frequency of letters in a sentence - python

I am a beginner with python and I want to make a program that can show the highest frequency of a letter in a given sentence. But, the program only works with one value, and only displays one of the letters that has the highest frequency.

I've already tried creating a list so that the biggest values will be added to it so that it will display multiple letters with their values. But, the problem is that the first value will always appear because it's greater than 0.

sentencecount = input("Please enter a sentence:\n")
print(f"The length of your sentence is {len(sentencecount)}.")
lettercount = {}
for i in sentencecount:
    if i in lettercount:
        lettercount[i] += 1
    else:
        lettercount[i] = 1
print(lettercount)
maximum=0
x='a'
listofletters = []
for x, y in lettercount.items():
    if y >= maximum:
        maximum=y
        letter =x
        listofletters.append(letter)
        listofletters.append(maximum)
print(listofletters)

i suggest you use collections.Counter :

from collections import Counter

sentence = "aaaabbbbcccc"

counter = Counter(sentence.lower().strip())
print(counter)  # Counter({'a': 4, 'b': 4, 'c': 4})
print(counter.most_common(1))  # [('a', 4)]

the lower() and strip() methods ensure you get the same result as above for 'a Aaabb Bbc cc C' .

if you wanted to select all the letters that are the most frequent:

from collections import Counter

sentence = "aaaabbbbcccc"

counter = Counter(sentence.lower().strip())
most_common = counter.most_common()

max_occurrence = most_common[0][1]
res = [letter for letter, occurrence in most_common if occurrence == max_occurrence]
 # ['a', 'b', 'c']

To get the list of most occuring values,

from collections import Counter
#switch the string to lower case if needed
s="abbbcdacabda"
counts=dict(Counter(s))
most_occuring_letters = [k for k,v in counts.items() if v == max(counts.values())]

result - ['a','b']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM