Напишите функцию, которая принимает текстовую строку и возвращает наиболее часто встречающееся слово и количество его вхождений. Игнорируйте регистр и знаки препинания.
Пример:
text = "Python is great, and Python is fun! Learning Python is rewarding."
result = most_common_word(text)
print(result)
# Ожидаемый результат: ('python', 3)
Решение задачи🔽
import re
from collections import Counter
def most_common_word(text):
words = re.findall(r'\b\w+\b', text.lower())
counter = Counter(words)
return counter.most_common(1)[0]
# Пример использования:
text = "Python is great, and Python is fun! Learning Python is rewarding."
result = most_common_word(text)
print(result)