Search⌘ K
AI Features

A File Of Patterns

Explore how to separate pluralization rules from code by storing patterns in an external file. Learn to read and parse this file with Python's open and with statements, then apply closures and generators to dynamically build functions for pluralizing words. This lesson helps you organize data and code efficiently.

We'll cover the following...

You’ve factored out all the duplicate code and added enough abstractions so that the pluralization rules are defined in a list of strings. The next logical step is to take these strings and put them in a separate file, where they can be maintained separately from the code that uses them.

First, let’s create a text file that contains the rules you want. No fancy data structures, just whitespace-delimited strings in three columns. Let’s call it plural4-rules.txt.

[sxz]$               $    es
[^aeioudgkprt]h$     $    es
[^aeiou]y$          y$    ies
$                    $    s
...