【问题标题】:counting alphabets from file python [duplicate]从文件python计算字母[重复]
【发布时间】:2013-09-02 17:10:50
【问题描述】:

从 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 次的任何字母,我不想打印它,, 如何解决这个问题?请帮忙

【问题讨论】:

  • 你的代码有什么问题?
  • 它不打印它给出错误,不能将 int 隐式更改为 str。
  • 使用str(word.count(alpha))
  • 如果单词存在零次我不想打印,该怎么做

标签: python python-3.x


【解决方案1】:
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}

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2017-04-20
    • 2019-06-20
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多