python - 计算字符串中字母的频率(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")
解决方案
如果需要,您可以使用自定义消息检查输入if else
和raise
错误
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")
推荐阅读
- ruby - 在 BFS 中重建图中的最短路径
- docker - 恐慌:无法引导订购者。读取创世块文件时出错:打开/etc/hyperledger/fabric/genesisblock:没有这样的文件或目录 - 无法解析
- php - 在 mysql 中查找日期大于 Now 的行
- unity3d - 如何使用您在 Text Mesh Pro 中统一导入的字体
- javascript - 在一个集合中使用嵌入文档和多个模式,猫鼬
- c++ - 在构造之前使用的静态链接库中的静态变量
- vue.js - 单击按钮时更新元素不起作用
- r - 使用 R,如何准备一个带有可选“导入”的库?
- ios - 使用 xamarin 插件“ImageCropper.Forms”时如何隐藏“拍照”菜单项
- flutter - Flutter ListView:onDismissed时只调用列表中的一项名称