【问题标题】:Counting the Frequency of Letters in a string (Python) [closed]计算字符串中字母的频率(Python)[关闭]
【发布时间】:2019-06-04 18:16:05
【问题描述】:

所以我试图在不使用 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")

【问题讨论】:

  • 如介绍性导览中所述,此站点是有用问题及其答案的存储库,不是帮助论坛。我们不会进行详细的格式化工作,也不会为您查找输入验证:那是您的工作。请参观,访问帮助中心,尤其是阅读how to ask"Can Someone Help Me?" is not a valid SO question 以了解如何有效地使用本网站。
  • 如果len(originalinput)==0: 抛出错误?不过,您到底在数什么还不清楚。为什么在实际计算字母频率时会标记词频
  • 请解释为什么没有字典。
  • -1 并投票删除,因为这里的编辑使现有答案无效,我不确定如果它发生在关闭后,我是否适合回滚这样的编辑,我不能无论如何,看看这个 Q 具有持久的价值。
  • 我同意我在发布此内容时并没有认真考虑

标签: python frequency-analysis


【解决方案1】:

如果需要自定义消息,您可以使用 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")

【讨论】:

  • 谢谢,这真的很有用!
【解决方案2】:

我建议使用收藏库中的 Counter。

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

【讨论】:

    【解决方案3】:

    正如@BlueSheepToken 提到的,您可以使用简单的if else 语句。下面是您的代码,其中包含提到的内容。

    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)
    

    在这种情况下,使用defaultdict 会有所帮助,因为所有未使用的keys 都将是0

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2023-03-25
      • 2017-04-20
      • 2018-09-08
      • 2012-06-04
      • 2016-05-18
      • 2016-07-25
      相关资源
      最近更新 更多