我正在尝试制作一个 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'