Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Preprocess Text with Python

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Preprocess Text with Python. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Capgemini Government Solutions is preparing text features for a document-analysis pipeline. Implement a deterministic preprocessing function that converts raw ASCII text into normalized token frequencies.

For each input string:

  1. Convert letters to lowercase.
  2. Extract tokens consisting only of contiguous ASCII letters and digits. Punctuation and other separators are delimiters.
  3. Remove tokens present in stop_words, which should be matched case-insensitively.
  4. Apply these simple normalization rules, in order: remove ing, ed, es, or a final s when the remaining token has at least three characters. Do not remove a final s when the token ends in ss.
  5. Remove normalized tokens shorter than min_length.
  6. Return a dictionary mapping each remaining token to its frequency. Preserve no information about token positions.

The input text contains only ASCII characters. Stemming is intentionally simple and does not need to handle every English word.

Formal Specification

Implement preprocess_text(text, stop_words, min_length). text is a string, stop_words is a list of strings, and min_length is a positive integer. Return a dictionary from normalized string tokens to integer counts. Return {} when no tokens remain.

Constraints

  • 1 <= len(text) <= 10^5
  • 0 <= len(stop_words) <= 10^4
  • 1 <= min_length <= 20
  • Tokens and stop words contain at most 32 ASCII letters or digits
  • The input text contains only ASCII characters

Function Signature

def preprocess_text(text, stop_words, min_length):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output