Counting the number of letters in a string alphabetically - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Counting the number of letters in a string alphabetically (/thread-16610.html) |
Counting the number of letters in a string alphabetically - TreasureDragon - Mar-06-2019 This is what I have so far and it is able to print out how many times a letter was printed but in order which it shows up in the string. I want it to first categorize by the number of times it popped up like the example output: (Also mine counts spaces, punctuations, etc. too but I don't want that) Sentence Statistics : e appeared 3 times . a appeared 2 times . g appeared 2 times . l appeared 2 times . o appeared 2 times . c appeared 1 times . d appeared 1 times . i appeared 1 times . m appeared 1 times . n appeared 1 times . t appeared 1 times . w appeared 1 times .Yes with the space between >1 and 1. This is what I have: string = input("Enter a Sentence: ") print(f"\nSentence Statistics:") one = 0 from collections import Counter count = Counter(string) for i in string: if count[i] == 1 and one == 0: print(f"\n{i} appeared {count[i]} times.") one += 1 elif count[i] == 1 and one >= 1: print(f"{i} appeared {count[i]} times.") if count[i] > 1: print(f"{i} appeared {count[i]} times.") RE: Counting the number of letters in a string alphabetically - Yoriz - Mar-06-2019 from collections import Counter import string test_string = 'Sentence Statistics' counter = Counter(test_string) for item, count in counter.most_common(): if item in string.ascii_letters: print(f'{item} appeared {count} times')
RE: Counting the number of letters in a string alphabetically - TreasureDragon - Mar-07-2019 (Mar-06-2019, 10:01 PM)Yoriz Wrote:from collections import Counter import string test_string = 'Sentence Statistics' counter = Counter(test_string) for item, count in counter.most_common(): if item in string.ascii_letters: print(f'{item} appeared {count} times') Nice. It's working like a charm. Just how do I alphabetize within the same amount of appearances? Also how do I make it case-insenstitive? Here's the updated code: from collections import Counter import string istring = input("Enter your sentence: ") counter = Counter(istring) one = 0 print(f"\nSentence Statistics:") for item, count in counter.most_common(): if item in string.ascii_letters: if count != 1: print(f'{item} appeared {count} times.') if count == 1 and one == 0: one += 1 print(f'\n{item} appeared {count} times.') elif count == 1 and one != 0: print(f'{item} appeared {count} times.') |