首页 > 解决方案 > 计算字符串中字母的频率(Python)

问题描述

所以我试图在不使用python字典的情况下计算用户输入字符串中字母的频率......我希望输出如下(以字母H为例)

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

我遇到的问题是程序按字母顺序打印字母,但我希望程序按照输入中给出的顺序打印字母的频率......

例如,如果我输入“Hello”,程序将打印

"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)"

但我希望输出如下

"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)"

这是我到目前为止的代码:

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")

标签: pythonfrequency-analysis

解决方案


如果需要,您可以使用自定义消息检查输入if elseraise错误

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

作为一个方面没有,input()就足够了,无需添加引号""

编辑:这个问题已被编辑,最初的问题是检查输入是否为空。

第二次编辑:

如果您希望您的代码在输出中打印字母,则应该迭代您的单词而不是字母表:

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

推荐阅读