计算一个字母被使用的次数

Count the number of times a letter is used

有了这个,我不仅需要统计一个单词中字母出现的频率,还需要吐出未使用的字母。

alphabetList = ["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"]


def Checksums():
    for i in alphabetList:

        character = i
        myString = Phrase
        myList = []

        for i in myString:
            myList.append(i)

        myList = myList.sort()
        print myList

        count = 0
        for i in myList:
            if i == character:
                count = count +1
            else:
                continue
        print("There are ", count, " occurrences of ", character )


#input
Phrase = str(raw_input("Enter a Phrase: "))

Phrase = Phrase.lower()
# print (Phrase)
Phrase = Phrase.replace(" ", "")
# print Phrase

Checksums()

输入示例可以是:

aaA cC D <br>

返回的是

"There were '3' occurrences of the letter 'a'"<br>
"There were '2' occurrences of the letter 'c'"<br>
"Only 1 'd'"<br>
"The remaining letters are unused": b, e, etc...

我尝试使用字母列表并循环浏览它,但出现以下错误:

TypeError: 'NoneType' object is not iterable

你可以试试这个

alphabetList = ["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"]
def occurence_counter(phrase):
    unused_letters = ""
    for alphabet in alphabetList:
        count = phrase.count(alphabet)
        if count > 1:
            print("There are ", count, " occurrences of ", alphabet )
        else:
            unused_letters = unused_letters + alphabet
    print("The remaining letters are unused" + unused_letters)
Phrase = str(input("Enter a Phrase: "))

Phrase = Phrase.lower()
occurence_counter(Phrase)

在您的函数中将 myList = myList.sort() 替换为 myList.sort()

一些简化代码的方法

首先,计算字符串中每个字母出现的次数,使用字典:

d = {};
for c in myString:
     d[c] = (d[c]+1) if (c in d) else 1

然后打印每个字母的统计数据:

# used letters:
for k in d:
    print("There are ", d[k], " occurrences of ", k)


#unused letters
for o in range(ord('a'),ord('z')):
   k = chr(o)
   if not (k in d):
       print("No occurrence of ", k, " in string")

或合并:

for o in range(ord('a'),ord('z')):
   k = chr(o)
   if not (k in d):
       print("No occurrence of ", k, " in string")
   else:
       print("There are ", d[k], " occurrences of ", k)

使用 Python 的 Counter and a set 来确定丢失的键,导致:

import string
from collections import Counter


def check(phrase):
    phrase = phrase.lower().replace(" ", "")
    phrase = Counter(phrase)

    for counts in phrase.items():
        print ("There were %s occurrences of the letter %s" % counts[::-1])

    missingCharacter = set(string.ascii_lowercase) - set(phrase.keys())
    print("The remaining letters are unused: %s" % ','.join(missingCharacter))


check('aaA cC D')

输出:

There were 3 occurrences of the letter a
There were 2 occurrences of the letter c
There were 1 occurrences of the letter d
The remaining letters are unused: b,e,g,f,i,h,k,j,m,l,o,n,q,p,s,r,u,t,w,v,y,x,z