信件计数程序

时间:2015-05-11 20:01:33

标签: python

在我的字母计数功能中,何时使用此代码

 from collections import Counter
import string
pickedletter= ()
count = 0
word = ()


def count_letters(word):
    global count
    wordsList = word.split()
    for words in wordsList:
        if words == pickedletter:
            count = count+1
    return count

word = input("what do you want to type? ")
pickedletter = input("what letter do you want to pick? ")
print (count_letters(word))

我知道某个字母的数量是0,无论如何。例如,这是我在命令提示符

中得到的内容
what do you want to type? rht
what letter do you want to pick? r
0
>>>

你如何解决这个问题,以确定字母出现在字符串中的次数?

3 个答案:

答案 0 :(得分:3)

有一种方法已经计算出一个字符的出现次数。对于不区分大小写的情况,请使用String.lower()

print (word.count(pickedletter))

答案 1 :(得分:0)

要计算完全字符,您可以使用内置count method

>>> mystring = "This is a test."
>>> mystring.count("t")
2

如果您想计算,无论案例,您都可以使用str.lower method

>>> mystring = "This is a test."
>>> mystring.lower().count("t")
3

您必须lower字符串,因为Tt的字符代码不相同。他们分别是84和116。

在你的功能中,它看起来像这样:

def count_letters(word):
    return word.count(pickedletter)

或者

def count_letters(word):
    return word.lower().count(pickedletter)

编辑(感谢abarnert)

如果您打算在非英语语言中使用此功能,则应使用casefold method代替。但是,这仅适用于Python 3。

>>> mystring = "This is a test."
>>> mystring.casefold().count("t")
3

答案 2 :(得分:0)

考虑到您已导入Counter,最简单的方法就是:

from collections import Counter

word = input('What do you want to type? ')
bag = Counter(word)
pickedLetter = input('What letter do you want to pick? ')
print(bag.get(pickedLetter, 0))