如何知道每个字母的频率?

1 投票
4 回答
804 浏览
提问于 2025-04-18 01:19

我已经这样做过了,但感觉太复杂了,有没有更简单的方法?提前谢谢你!

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

如果你不想使用 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))
0

使用for循环。下面是一个for循环的例子,它可以用来计算字母'a'和'b'的数量:

for character in "ab":
    print(character + " has " + str(all_words.count(character)) + " occurences.")
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

这样你只需要处理字符串一次,而不是每个字母都去countCounter 基本上就是一个字典,但多了一些很有用的功能。

另外,你还需要考虑大小写——"A" 是不是应该和 "a" 算作同一个,还是说它们是不同的?

1

当然,你可以把代码简化到差不多两行。不过,如果你不太懂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])))

撰写回答