如何计算单词中的字母? [英] How to count the letters in a word?

查看:92
本文介绍了如何计算单词中的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个Python脚本,用于对我的Hangman游戏中随机选择的单词中的字母数量进行计数.

I am trying to make a Python script which counts the amount of letters in a randomly chosen word for my Hangman game.

我已经在网上四处张望,但是我能找到的大多数东西都是用单词来计算特定的字母.经过更多的环顾后,我最终发现了这一点,由于某种原因,它不起作用.如果有人指出错误,将不胜感激.

I already looked around on the web, but most thing I could find was count specific letters in a word. After more looking around I ended up with this, which does not work for some reason. If someone could point out the errors, that'd be greatly appreciated.

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)

推荐答案

首先,您的代码包含一个非常重要的错误,应理解:

First off, your code contains an error that is rather important to understand:

wordChosen.lower().count['a', 'b'] #...

count函数,因此它要求您用括号而不是方括号将其参数括起来!

count is a function and so it requires you to surround its parameters with parentheses and not square brackets!

接下来,您应该尝试参考 Python文档 a> .那应该可以帮助您了解为什么您的方法行不通.

Next you should try to refer to Python Documentation when using a function for the first time. That should help you understand why your approach will not work.

现在解决您的问题.如果要计算字符串中的字母数,请使用len(wordChosen)来计算字符串中的字符总数.

Now to address your problem. If you want to count the number of letters in your string use len(wordChosen) which counts the total number of characters in the string.

如果要计算每个字母的频率,已经建议了几种方法.这是使用字典的另一种方法:

If you want to count the frequencies of each letter a few methods have already been suggested. Here is one more using a dictionary:

import string
LetterFreq={}
for letter in string.ascii_lowercase:
    LetterFreq[letter] = 0
for letter in wordChosen.lower():
    LetterFreq[letter] += 1

这有一个很好的好处,那就是将单词中不存在的所有字母默认为0:)

This has the nice perk of defaulting all letters not present in the word to a frequency of 0 :)

希望这会有所帮助!

这篇关于如何计算单词中的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆