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

2024-04-18 19:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经做过了,但是时间太长了,我怎么能做一个简单得多的方法呢?提前谢谢

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

Tags: 方法iscount时间alltherewordsprint
3条回答

当然,您可以将代码减少到几乎两行。但是,如果您不知道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])))

用于循环。for循环的一个示例,它将计算字母“a”和“b”:

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

答案是多种多样的——当然,当你第十次写出letter_X = all_words.count('X')时,你应该一直在想“也许for循环可以让我从这件事中解脱出来?”它会:

import string  

for character in string.ascii_lowercase:
    ...

类似地:

  • “我可以用dict而不是大量的独立变量,用字母作为键,以计数作为值吗?”在
  • “我是否需要将所有这些存储起来,然后再存储它们,或者我可以直接存储它们吗?”在

但是,这里最简单的方法是使用^{},例如:

^{pr2}$

这种方法只处理一次字符串,而不是对每个字母进行countCounter基本上是一个具有一些额外有用功能的字典。在

另外,您还需要考虑大小写-"A"是否应计为"a",反之亦然,还是它们是分开的?在

相关问题 更多 >