#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
p4-wordfreq.py — word frequency counter (no external dependencies).

Reads UTF-8 text from stdin, lowercases it, splits on whitespace and
punctuation, counts word frequencies, and prints the top 20 words in
descending order, one per line: "<count> <word>".

A leading UTF-8 BOM (EF BB BF), if present, is stripped before counting.
Empty tokens from the split are skipped.
"""

import re
import sys
import unicodedata
from collections import Counter

# The spec asks for splitting on whitespace AND punctuation using the
# pattern `[\s\p\u]+` with the UNICODE flag. That literal pattern cannot be
# compiled by CPython's `re` module — `\p` and `\u` are "bad escape" errors
# (stdlib `re` has no `\p{...}` property escapes). We implement the same
# intent with a character class that really contains the characters:
#   * `\s`            — all whitespace (Unicode-aware via the UNICODE flag)
#   * every Unicode Punctuation (P) code point, escaped for use in `re`,
#     built once with unicodedata from the standard library.
_PUNCT = "".join(
    chr(cp)
    for cp in range(0x110000)
    if unicodedata.category(chr(cp))[0] == "P"
)
_SPLIT_RE = re.compile(r"[\s" + re.escape(_PUNCT) + r"]+", re.UNICODE)


def split_words(text: str):
    """Split text on runs of whitespace/punctuation, skipping empty tokens."""
    return [token for token in _SPLIT_RE.split(text) if token]


def main() -> None:
    data = sys.stdin.buffer.read()
    # 'utf-8-sig' transparently strips a leading BOM if present.
    text = data.decode("utf-8-sig")
    text = text.lower()
    counts = Counter(split_words(text))
    # Top 20 by frequency, descending; ties keep first-seen order.
    for word, count in counts.most_common(20):
        print(f"{count} {word}")


if __name__ == "__main__":
    main()
