python - 如何计算单词中的字母?

标签 python counter words letters

<分区>

我正在尝试制作一个 Python 脚本来计算我的 Hangman 游戏中随机选择的单词中的字母数量。

我已经在网上四处寻找,但我能找到的大部分内容都是计算单词中的特定字母。环顾四周后,我最终得到了这个,但由于某种原因它不起作用。如果有人能指出错误,将不胜感激。

wordList = ["Tree", "Fish", "Monkey"]
wordChosen = random.choice(wordList)
wordCounter = wordChosen.lower().count['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print(wordCounter)

最佳答案

您是否在寻找 collections.Counter

>>> import collections
>>> print(collections.Counter("Monkey"))
Counter({'M': 1, 'y': 1, 'k': 1, 'o': 1, 'n': 1, 'e': 1})
>>> print(collections.Counter("Tree"))
Counter({'e': 2, 'T': 1, 'r': 1})

>>> c = collections.Counter("Tree")
>>> print("The word 'Tree' has {} distinct letters".format(len(c)))
The word 'Tree' has 3 distinct letters
>>> print("The word 'Tree' has {} instances of the letter 'e'".format(c['e']))
The word 'Tree' has 2 instances of the letter 'e'

关于python - 如何计算单词中的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32187934/

相关文章:

Python单词计数器对单词是否被引号括起来敏感?

python - 使用 Counter 计算带空格的字符串的出现次数

Python Tf idf算法

python - 如何在 python 中为列创建转换矩阵?

python - Django Rest框架和Redis

Python 2.7 有意使用 .items 而不是 .iteritems

javascript - 单击按钮而不是按键时执行脚本

python - 如何使用 Doxygen 记录 Python 代码

Python:从 URL 读取 HTML 源并将日期获取到程序中

C++ 作业 - 计算字数