بتل کد Battle Codeدارد باز می‌شود…

جواب «A Reusable Text Module» چالش 8 از جلسه‌ی 45

سؤال

کد را مثل یک ماژول قابل استفاده‌ی مجدد سازمان دهید: سه تابع عمومی normalize(text) (حروف کوچک و حذف .,!?)، word_counts(text) (یک Counter از کلمات نرمال‌شده) و top_words(text, n) (لیست n کلمه‌ی پرتکرار، در تساوی به ترتیب اولین دیدن)، و یک main() که یک خط متن و سپس n را بخواند و هر کلمه را به شکل <word>: <count> چاپ کند؛ main فقط زیر گارد __name__ صدا زده شود. برای The cat. The dog! the END و 2:
the: 3
cat: 1

راهنما

هر تابع فقط یک کار کند و از تابع قبلی استفاده کند: top_words روی word_counts و آن روی normalize ساخته می‌شود.

یک جواب درست

from collections import Counter

_PUNCTUATION = str.maketrans("", "", ".,!?")


def normalize(text):
    return text.lower().translate(_PUNCTUATION)


def word_counts(text):
    return Counter(normalize(text).split())


def top_words(text, n):
    return word_counts(text).most_common(n)


def main():
    text = input()
    n = int(input())
    for word, count in top_words(text, n):
        print(f"{word}: {count}")


if __name__ == "__main__":
    main()

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن