Посчитайте, сколько раз использовалась буква - PullRequest
0 голосов
/ 24 февраля 2020

При этом мне нужно не только посчитать частоту букв в слове, но и выложить неиспользуемые буквы.

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' не повторяется

Ответы [ 4 ]

1 голос
/ 24 февраля 2020

Использование Python ' Counter и 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
0 голосов
/ 24 февраля 2020

замените myList = myList.sort() на myList.sort() в вашей функции.

0 голосов
/ 24 февраля 2020

Некоторые способы упростить ваш код

Сначала, чтобы подсчитать количество вхождений каждой буквы в строке, используйте dict:

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)
0 голосов
/ 24 февраля 2020

Вы можете попробовать использовать это

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...