Data science: Normalise free-text answers

A survey asked for a favourite food in free text. Normalise the answers so that variants are counted together.

What to build

A program that normalises free-text answers and counts them.

Requirements

  • Normalise each answer: lower case; remove every character that is not a letter a to z or a space; split into words; for each word, if it ends with ies (and is longer than 3 letters) replace that with y, else if it ends with oes remove the es, else if it ends with s but not ss remove the s; join the words with single spaces.
  • Print ANSWER: COUNT for every normalised answer, by count from highest, equal counts in alphabetical order. If some answers are empty after normalising, finally print blank: K.

Input

Line 1: n. Then n answers, one per line.

Output

The counts, then perhaps the blank line.

Constraints

1 ≤ n ≤ 1000.

Example

Input:

6
Mango
 mangoes!
MANGOS
Cherries
cherry

Output:

mango: 3
cherry: 2
blank: 1

Why it works

A fixed sequence of rules turns every variant into one form, so a dictionary of counts can do the rest, and printing blanks separately keeps empty answers from looking like a real response.

Examples

Example 1 · Input
6
Mango
 mangoes!
MANGOS
Cherries
cherry

Expected output
mango: 3
cherry: 2
blank: 1
Example 2 · Input
3
Ice cream
ice  creams
Glass
Expected output
ice cream: 2
glass: 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Lower-case, replace every character that is not a letter or a space with nothing, then split into words, which also collapses spaces.

Hint 2

Apply the plural rules to each word in order: ies → y, oes → o, and a final s (but not ss) is removed.

Solution

Show one correct solution (try it yourself first)
import re

n = int(input())


def singular(word):
    if word.endswith("ies") and len(word) > 3:
        return word[:-3] + "y"
    if word.endswith("oes"):
        return word[:-2]
    if word.endswith("s") and not word.endswith("ss"):
        return word[:-1]
    return word


counts = {}
blank = 0
for _ in range(n):
    words = re.sub(r"[^a-z ]", "", input().lower()).split()
    answer = " ".join(singular(w) for w in words)
    if answer == "":
        blank += 1
    else:
        counts[answer] = counts.get(answer, 0) + 1

for answer, count in sorted(counts.items(), key=lambda item: (-item[1], item[0])):
    print(f"{answer}: {count}")
if blank:
    print("blank:", blank)

Lesson: Dates, times and text →