Решение 1. Частотный анализ
from collections import Counter
def count_words(text):
words = text.lower().replace(".", "").replace(",", "").split()
return dict(Counter(words))
text = "This is a test. This test is only a test."
print(count_words(text))Подготовка текста отделена от подсчёта, Counter получает уже нормализованные слова.
Решение 2. Группировка по факультетам
from collections import defaultdict
def group_students_by_faculty(students):
result = defaultdict(list)
for name, faculty in students:
result[faculty].append(name)
return dict(result)
students = [("Иван", "Физика"), ("Мария", "Математика"), ("Пётр", "Физика")]
print(group_students_by_faculty(students))dict(result) превращает defaultdict в обычный словарь для чистого вывода.
Решение 3. Counter most_common
from collections import Counter
counter = Counter("banana")
print(counter.most_common(2))most_common сортирует элементы по убыванию частоты.