-1

从 file.txt 读取文本并计算其中每个字母的数量,输出应该像 a=2(如果有 2 个 a)和 b=6(如果有 6 个 b)到目前为止我已经做了这么多,这会打印每个字母,但我想打印仅存在的字母。

f= open('cipher.txt')
word= " ".join(line.strip() for line in f)
word=word.lower()
alpha="abcdefghijklmnopqrstuvwxyz"
alpha=list(alpha)
for i in alpha:
  print(i+"="+str(word.count(i)))

但是,如果使用了 0 次的任何字母表,我不想打印,如何解决这个问题?请帮忙

4

1 回答 1

0
import letters
s = 'hello world'
{a:s.count(a) for a in string.letters if s.count(a) != 0}
OUTPUT:
{'d': 1, 'e': 1, 'h': 1, 'l': 3, 'o': 2, 'r': 1, 'w': 1}
于 2013-09-02T08:24:10.283 回答