你怎么知道每个字母的频率?

时间:2014-04-04 10:32:41

标签: python counting

我已经完成了这个但是太长了,我怎么能做一个更简单的方法呢?提前致谢

letter_a = all_words.count('a')

letter_b = all_words.count('b')

letter_c = all_words.count('c')

letter_d = all_words.count('d')

letter_e = all_words.count('e')

letter_f = all_words.count('f')

letter_g = all_words.count('g')

letter_h = all_words.count('h')

letter_i = all_words.count('i')

letter_j = all_words.count('j')

letter_k = all_words.count('k')

letter_l = all_words.count('l')

letter_m = all_words.count('m')

letter_n = all_words.count('n')

letter_o = all_words.count('o')

letter_p = all_words.count('p')

letter_q = all_words.count('q')

letter_r = all_words.count('r')

letter_s = all_words.count('s')

letter_t = all_words.count('t')

letter_u = all_words.count('u')

letter_v = all_words.count('v')

letter_w = all_words.count('w')

letter_x = all_words.count('x')

letter_y = all_words.count('y')

letter_z = all_words.count('z')



print("There is:\n"


 "A:",letter_a,",\n"

  "B:",letter_b,",\n"

  "C:",letter_c,",\n"

  "D:",letter_d,",\n"

  "E:",letter_e,",\n"

  "F:",letter_f,",\n"

  "G:",letter_g,",\n"

  "H:",letter_h,",\n"

  "I:",letter_i,",\n"

  "J:",letter_j,",\n"

  "K:",letter_k,",\n"


  "L:",letter_l,",\n"

  "M:",letter_m,",\n"

  "N:",letter_n,",\n"

  "O:",letter_o,",\n"

  "P:",letter_p,",\n"

  "Q:",letter_q,",\n"

  "R:",letter_r,",\n"

  "S:",letter_s,",\n"

  "T:",letter_t,",\n"

  "U:",letter_u,",\n"


  "V:",letter_v,",\n"

  "W:",letter_w,",\n" 

  "X:",letter_x,",\n"

  "Y:",letter_y,",\n"

  "Z:",letter_z,

  "\n")

4 个答案:

答案 0 :(得分:7)

有各种答案 - 当然,正如你第十次写出letter_X = all_words.count('X')一样,你应该一直在思考“也许一个for循环会让我免于这个?”它会:

import string  

for character in string.ascii_lowercase:
    ...

类似地:

  • “我可以使用dict而不是许多单独的变量,将字母作为键,将计数作为值吗?”
  • “我是否需要存储所有这些然后 print他们,或者我可以直接 print他们?”

但是,最简单的方法是使用collections.Counter,例如:

>>> from collections import Counter
>>> counter = Counter("foo bar baz")
>>> counter
Counter({'a': 2, ' ': 2, 'b': 2, 'o': 2, 'f': 1, 'r': 1, 'z': 1})
>>> counter['a']
2
>>> counter['c']
0

这样您只需处理一次字符串,而不是count每个字母。 Counter基本上是一个包含一些额外有用功能的字典。

此外,您需要考虑案例 - "A"应该计为"a",反之亦然,或者它们是否分开?

答案 1 :(得分:0)

用于循环。 for循环的一个例子,它会计算字母'a'和'b':

for character in "ab":
    print(character + " has " + str(all_words.count(character)) + " occurences.")

答案 2 :(得分:0)

绝对可以将代码减少到两行。但是,如果您不了解python语法

,可读性可能会成为一个问题
import string
all_words = 'this is me'
print("there is:\n {0}".format('\n'.join([letter+':'+str(all_words.count(letter) + all_words.count(letter.lower())) for letter in string.uppercase])))

答案 3 :(得分:0)

如果您不想使用collection.Counter和其他库(例如string.ascii_uppercase)并构建自己的算法,可以试试这个:

all_words = 'asasasaassasaasasasasassa'
upper_words = all_words.upper()
letter_freq = {}
for letter in set(upper_words):
    l etter_freq[letter] = upper_words.count(letter)

for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
    print '%s: %d'%(letter, letter_freq.get(letter, 0))