Почему я часто получаю буквы, а не слова? - PullRequest
0 голосов
/ 14 июля 2020
text = input('Enter a line of text. (You might consider coping and pasting text'): 
text = text.lower()

words=text.split()
words=sorted(words)
wordsdict={}

for words in text:
    wordsdict.setdefault(words,0)
    wordsdict[words] = wordsdict[words]+1

print(wordsdict)

1 Ответ

0 голосов
/ 14 июля 2020

Причина в том, что у вас есть words = text.split(), но вы никогда не перебираете words в своем коде. У вас do есть for words in text:, где words - это не то, что вы определили ранее, это новая переменная на каждой итерации.

Итак, for words in text: фактически перебирает каждый символ в text, где text - строка.

Вот исправленная версия:

text = input('Enter a line of text. (You might consider coping and pasting text): ')
text = text.lower()

words=text.split()
words=sorted(words)

wordsdict={}

for word in words:
    wordsdict.setdefault(word,0)
    wordsdict[word] = wordsdict[word]+1

print(wordsdict)
...