【问题标题】:Count the frequency of letters in a string, not blank spaces, numbers, or punctuation计算字符串中字母的频率,而不是空格、数字或标点符号
【发布时间】:2020-03-02 14:16:51
【问题描述】:
def count_letters(text):
  result = {}
  # Go through eactter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter in text:
       result[letter.lower()]=result.get(letter,0)+1
    # Add or increment the value in the dictionary
  for k  in result:
    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}

【问题讨论】:

  • 你可以通过if letter.isalpha()来检查chatacter是否是一个字母
  • 实际上我必须计算字母的频率,但没有空格和“。”和特殊字符

标签: python string dictionary


【解决方案1】:

您可以将Counterfilter 一起使用。

import string
from collections import Counter
Counter(filter(lambda x:x in string.ascii_letters,_str.lower()))

Counter({'m': 1,
         'a': 1,
         't': 1,
         'h': 1,
         'i': 1,
         's': 1,
         'f': 1,
         'u': 1,
         'n': 1})

【讨论】:

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