Counting the Frequency of Letters in a string (Python)

时间:2019-01-09 22:14:03

标签: python frequency-analysis

So I'm trying to count the frequency of letters in a user inputted string without using python dictionaries... I want the output to be as follows (using letter H as an example)

"The letter H occurred 1 time(s)." 

The problem I have is that the program prints the letters in alphabetical order but I want the program to print the frequency of the letters in the order that they were given in the input...

an example of this would be if I entered "Hello" the program would print

"The letter e occurred 1 time(s)"
"The letter h occurred 1 time(s)"
"The letter l occurred 2 time(s)"
"The letter o occurred 1 time(s)"

but I want the output to be as follows

"The letter h occurred 1 time(s)"
"The letter e occurred 1 time(s)"
"The letter l occurred 2 time(s)"
"The letter o occurred 1 time(s)"

This is the code that I have so far:

originalinput = input("")
if originalinput == "":
    print("There are no letters.")
else:
  word = str.lower(originalinput)

  Alphabet= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

  for i in range(0,26): 
    if word.count(Alphabet[i]) > 0:
      print("The letter", Alphabet[i] ,"occured", word.count(Alphabet[i]), "times")

3 个答案:

答案 0 :(得分:0)

You could just check the input with if else and raise an Error if needed with a custom message

if original_input == "":
    raise RuntimeError("Empty input")
else:
    # Your code goes there

As a side not, input() is enough, no need to add quotes ""

Edit: This question was edited, the original question was to check if an input is empty.

Second edit:

If you want your code to print letters as in your output, you should iterate over your word instead over your alphabet:

for c in word:
     print("The letter", c ,"occured", word.count(c), "times")

答案 1 :(得分:-1)

As @BlueSheepToken mentioned you can use simple if else statement. Here is your code below incorporating things that are mentioned.

from collections import defaultdict

originalinput = input()

if originalinput == "":
    raise RuntimeError("Empty input")
else:

    result = defaultdict(int)

    for char in list(originalinput.lower()):
        result[char] += 1

    for letter, num in result.items():
        print(f'The letter {letter} occurred {num} time(s)')  

    #Hello
    #The letter h occurred 1 time(s)
    #The letter e occurred 1 time(s)
    #The letter l occurred 2 time(s)
    #The letter o occurred 1 time(s)

Using defaultdict will help you in this case as all the unused keys will be 0.

答案 2 :(得分:-1)

I would recommend using Counter from the collections library.

    from collections import Counter

    print(Counter('sample text'))

    #Output: Counter({'t': 2, 'e': 2, 'l': 1, 's': 1, 'a': 1, ' ': 1, 'p': 1, 'm': 1, 'x': 1})