Форум сайта python.su
Код основной написан, остался лишь output.
Код находит самые частые слова в инпуте и их количество рядом.
При Input: On her 7th birthday there were 7 balloons in the air
and 7 candles on the chocolate cake.
Output должен выглядеть таким образом:
the 2
were 1
there 1
th 1
on 1
in 1
her 1
chocolate 1
candles 1
cake 1
birthday 1
balloons 1
and 1
air 1
On 1
Самое часто используемое слово сверху.
Помогите с последними строками кода, как можно оформить такой вот Output.
import sys import string def split(str): otvet = [] word = "" for i in str: if(i in string.ascii_letters): word += i elif word != "": otvet.append(word) word = "" if word != "": otvet.append(word) return otvet def count(str): counts = dict() words = split(str) for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts data = sys.stdin.read() counts = count(data)
Отредактировано benny (Ноя. 17, 2021 17:42:23)
Офлайн
import string def split(text): otvet = [] word = "" for i in text: if i in string.ascii_letters: word += i elif word != "": otvet.append(word) word = "" if word != "": otvet.append(word) return otvet def count(list_words): counts = dict() for word in list_words: counts[word] = counts.setdefault(word, 0) + 1 return sorted(list(counts.items()), key = lambda x : x[::-1], reverse = True) text = 'On her 7th birthday there were 7 balloons in the air\ and 7 candles on the chocolate cake' list_words = split(text) for word, num in count(list_words): print(word, num)
Отредактировано marvellik (Ноя. 18, 2021 18:08:56)
Офлайн