如何计算不包括空格和数字的文本中字母的出现频率?

新手上路,请多包涵

使用字典计算输入字符串中字母出现的频率。只应计算字母,不计算空格、数字或标点符号。大写字母应被视为与小写字母相同。例如,count_letters(“This is a sentence.”) 应该返回 {’t’: 2, ‘h’: 1, ‘i’: 2, ’s’: 3, ‘a’: 1, ‘e’: 3, ‘n’: 2, ‘c’: 1}

 def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

原文由 Yahia Naeem 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 468
2 个回答

这应该工作:

 >>> from collections import Counter
>>> from string import ascii_letters
>>> def count_letters(s) :
...     filtered = [c for c in s.lower() if c in ascii_letters]
...     return Counter(filtered)
...
>>> count_letters('Math is fun! 2+2=4')
Counter({'a': 1, 'f': 1, 'i': 1, 'h': 1, 'm': 1, 'n': 1, 's': 1, 'u': 1, 't': 1})
>>>

原文由 lenik 发布,翻译遵循 CC BY-SA 4.0 许可协议

def count_letters(text):
  result = {}
  text = text.lower()
  # Go through each letter in the text
  for letter in text:

    # Check if the letter needs to be counted or not
    if letter.isalpha() :
      # Add or increment the value in the dictionary
      count = text.count(letter)
      result[letter] = count
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

原文由 AKinsoji Hammed Adisa 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题