v9.1.1
Menu

Tokenize and Count

easyFREEText ProcessingNLP 1: Foundations

Given a string of text, split it into lowercase words (splitting on whitespace), and return a dictionary mapping each word to its frequency count.

Words should be converted to lowercase before counting. The output dictionary should be printed with keys in sorted order.

Example:

  • Input: "The cat sat on the mat"
  • After lowercasing and splitting: ["the", "cat", "sat", "on", "the", "mat"]
  • Frequencies: {"cat": 1, "mat": 1, "on": 1, "sat": 1, "the": 2}

Example

Input
The cat sat on the mat
Output
{'cat': 1, 'mat': 1, 'on': 1, 'sat': 1, 'the': 2}
Reasoning
  • Input: text is one line, The cat sat on the mat: six words separated by single spaces. Two of them, "The" and "the", differ only in capitalisation.
  • Normalise case: once every letter is lower case, "The" and "the" are the same token, so the word list becomes the, cat, sat, on, the, mat: six tokens but only five distinct words.
  • Count: each distinct word maps to how many times it occurs. "the" occurs at positions 1 and 5, so its count is 22; cat, sat, on and mat occur once each. The counts sum to 2+1+1+1+1=62 + 1 + 1 + 1 + 1 = 6, the token total.
  • Output: the dictionary {'cat': 1, 'mat': 1, 'on': 1, 'sat': 1, 'the': 2}, with keys in alphabetical order: c < m < o < s < t. Sentence position plays no part, which is why 'the' comes last even though it is the first word.
  • Notice: without lower-casing, The and the would be two separate keys, each with count 11.

Constraints

  • Input: A single line of text (string)
  • Split on whitespace only
  • Convert all words to lowercase before counting
  • Output: A dictionary printed with keys in sorted order
  • Words contain only alphabetic characters and whitespace

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.