Skip to content

02. Strings and text — Mini-project

The sales team exports order lines from the shop system every month. The export is messy: product names have stray spaces, so one product shows up under several spellings, and every count by product is wrong. Before anyone builds a dashboard, the team needs to know two things: does every line belong to a real product, and how many lines does each product have?

Write a script, product_report.py, that cleans the product names in the raw export, matches them to the official product catalog and prints an aligned report. The script also saves the report as a UTF-8 text file, so it can go into an e-mail or a ticket.

The project uses the core skills of module 02: reading text, the csv module for quoted fields, split() and join() to clean text, exact string matching, f-strings with nested format specs, a text table with a title bar and a total row, and writing text with an explicit encoding.

Two files from the course data:

File Rows Columns used
data/sales_raw.csv 1,200 sales lines product (column 7)
data/products.csv 30 products product_id, product, category, unit_price

data/sales_raw.csv is the raw export. 95 of its product names have stray spaces: 29 leading, 35 trailing and 31 with a double space inside. Some lines have quoted fields with commas ("January 7, 2023", "$1,299.00"), so split(",") cannot read them. data/products.csv is the catalog: one row per product, with the official spelling of each name. Both files are UTF-8.

Your script must:

  1. Read both files with encoding="utf-8" and parse them with csv.reader(). Skip the header rows.
  2. Clean every product name in the sales file with " ".join(name.split()). Count how many names changed.
  3. For each of the 30 catalog products, count the sales lines whose clean name equals the official name exactly.
  4. Compute each product’s share of all sales lines, the total of matched lines and the most frequent product.
  5. Print the report below, exactly. Keep every column width in a variable at the top of the script, and use nested format specs (f"{name:<{W_NAME}}"), so a width changes in one place.
  6. Build the report as a list of lines, join them with "\n", print the text and save it to output/product_report.txt with encoding="utf-8".
  7. End with assert checks: the catalog has 30 products, every sales line matched a product, and the saved file equals the printed text.

The expected report:

Expected output
=============== Sales lines per product (sales_raw.csv) ===============
ID Product Category Price Lines Share
-----------------------------------------------------------------------
P001 Wireless Earbuds Electronics 79.99 91 7.6%
P002 Noise-Cancelling Headphones Electronics 249.00 45 3.8%
P003 55-inch 4K Smart TV Electronics 1,299.00 15 1.2%
P004 14-inch Ultrabook Laptop Electronics 1,149.00 32 2.7%
P005 Smartwatch Series 5 Electronics 199.99 54 4.5%
P006 Espresso Machine Home 349.00 31 2.6%
P007 Robot Vacuum Home 299.99 31 2.6%
P008 Chef's Knife Set Home 129.95 51 4.2%
P009 Air Purifier Home 189.00 46 3.8%
P010 Cotton Bed Sheet Set Home 69.99 62 5.2%
P011 Waterproof Rain Jacket Clothing 119.00 42 3.5%
P012 Merino Wool Sweater Clothing 89.50 31 2.6%
P013 Slim Fit Jeans Clothing 59.99 57 4.8%
P014 Running Socks 3-Pack Clothing 14.99 59 4.9%
P015 Organic Cotton T-Shirt Clothing 19.99 65 5.4%
P016 Trail Running Shoes Sports 129.99 38 3.2%
P017 Non-Slip Yoga Mat Sports 34.99 50 4.2%
P018 Adjustable Dumbbells Sports 279.00 22 1.8%
P019 Fitness Tracker Sports 99.99 36 3.0%
P020 2-Person Camping Tent Sports 189.99 20 1.7%
P021 Harbor Lane Mysteries Books 16.99 44 3.7%
P022 Weeknight Kitchen Cookbook Books 29.99 26 2.2%
P023 A Brief History of Maps Books 24.50 26 2.2%
P024 Statistics Made Simple Books 34.99 36 3.0%
P025 The Mindful Runner Books 14.99 9 0.8%
P026 Vitamin C Face Serum Beauty 24.99 36 3.0%
P027 Hydrating Face Cream Beauty 32.00 40 3.3%
P028 Shampoo and Conditioner Set Beauty 21.50 36 3.0%
P029 Electric Toothbrush Beauty 59.99 27 2.2%
P030 Mineral Sunscreen SPF 50 Beauty 15.99 42 3.5%
-----------------------------------------------------------------------
Total 1,200 100.0%
=======================================================================
Sales lines read: 1,200
Product names cleaned: 95
Lines matched to catalog: 1,200
Lines not matched: 0
Most frequent product: Wireless Earbuds (91 lines)
  1. Create the file. Make product_report.py in your project folder, next to data/. Add a comment at the top that says what the script does and which files it reads.

  2. Define the settings. Put the two input paths, the output path and the six column widths at the top: ID 6, product 28, category 12, price 10, lines 7, share 8. Compute the total width (71) from them.

  3. Read the files. Use Path(...).read_text(encoding="utf-8").splitlines() and pass the lines to csv.reader(). Wrap it in list() and drop the header with [1:]. Print len() of both lists once to check: 1,200 and 30.

  4. Clean the names. Loop over the sales rows. Clean column 7 and add it to a list. Add raw != clean to a counter; True counts as 1. Check that the counter is 95.

  5. Count per product. Loop over the catalog rows. A catalog row has 6 fields: product_id, product, category, unit_cost, unit_price, launch_date. clean_products.count(name) gives the number of sales lines for that product. Keep the counts and the names in two lists.

  6. Build the table. Start with an empty list report. Append the title bar (=^), the header, a separator, one row per product, a separator, the total row and the closing bar. Text columns use <, number columns use >. The price is text in the catalog: convert it with float() before you use :,.2f.

  7. Add the summary. Compute the matched total with sum(counts) and the most frequent product with counts.index(max(counts)). Append the five summary lines with a fixed label width.

  8. Print and save. Join the lines with "\n", print the text, create the output/ folder and write the file with encoding="utf-8".

  9. Add self-checks and run the script with python product_report.py. Compare every line with the expected report, including the spaces.

A skeleton to start from:

product_report.py (starter)
# product_report.py: sales lines per product, from the raw export.
import csv
from pathlib import Path
# --- Settings ---
SALES_FILE = Path("data/sales_raw.csv")
CATALOG_FILE = Path("data/products.csv")
REPORT_FILE = Path("output") / "product_report.txt"
# TODO: the six column widths and the total width
# --- Read and clean ---
# TODO: read both files with csv.reader(); clean the sales product names
# --- Build the report lines ---
report = []
# TODO: title bar, header, separator, one row per product, total, summary
# --- Print and save ---
# TODO: join, print, write with encoding="utf-8"
# --- Self-checks ---
# TODO: at least three assert statements
Criterion Points Full points when
Runs as a script 2 python product_report.py runs with no error and prints the report
Correct parsing 2 both files are read with csv.reader() and encoding="utf-8"; quoted fields cause no shifted columns
Cleaning 2 names are cleaned with split() and join(); the count of cleaned names is 95
Matching 2 counts come from exact matches with the catalog names; all 1,200 lines match
Format specs 3 every number uses a spec (,.2f, ,, .1%); text left, numbers right; the output equals the expected report
Maintainable layout 2 widths are variables used in nested specs; header, rows and total share the same widths
Saved file 1 the report is saved as UTF-8 in output/, and the file equals the printed text
Self-checks 2 at least three meaningful assert statements
Total 16 13 or more: you are ready for module 03
  1. Cut product names longer than 20 characters to 19 characters plus … (one character, U+2026), so the table fits a narrow terminal. Hint: a precision on a string (:.19) cuts it.
  2. Add a column with the number of raw spellings of each product in the export. (Collect the raw names in a second list and use set().)
  3. Clean the region column (index 4) too, and add a second small table with the lines per region and a Missing row for "", N/A and -.
  4. Print the prices in European style (1.299,00) with str.maketrans() and translate().
  5. Save a second copy of the report encoded as latin-1, and compare the two file sizes. Explain the result: does the report contain any character that needs more than one byte in UTF-8? What changes if you add the … of stretch goal 1?

Try the project yourself first. Then compare your script with this one. Your names and comments can differ; your output must not.

Reference solution
product_report.py
# product_report.py: clean the product names in data/sales_raw.csv and print
# an aligned report of sales lines per product, checked against the catalog.
import csv
from pathlib import Path
# --- Settings ----------------------------------------------------------------
SALES_FILE = Path("data/sales_raw.csv")
CATALOG_FILE = Path("data/products.csv")
REPORT_FILE = Path("output") / "product_report.txt"
W_ID, W_NAME, W_CAT, W_PRICE, W_LINES, W_SHARE = 6, 28, 12, 10, 7, 8
WIDTH = W_ID + W_NAME + W_CAT + W_PRICE + W_LINES + W_SHARE
# --- Read and clean ----------------------------------------------------------
# The csv module handles the quoted fields ("January 7, 2023", "$1,299.00").
sales_text = SALES_FILE.read_text(encoding="utf-8")
catalog_text = CATALOG_FILE.read_text(encoding="utf-8")
sales_rows = list(csv.reader(sales_text.splitlines()))[1:] # [1:] skips the header
catalog_rows = list(csv.reader(catalog_text.splitlines()))[1:]
clean_products = []
messy = 0
for row in sales_rows:
raw_name = row[7]
clean_name = " ".join(raw_name.split()) # strip ends, collapse inner spaces
clean_products.append(clean_name)
messy += raw_name != clean_name # True counts as 1
# --- Build the report lines --------------------------------------------------
total_lines = len(sales_rows)
report = []
report.append(f"{' Sales lines per product (sales_raw.csv) ':=^{WIDTH}}")
report.append(
f"{'ID':<{W_ID}}{'Product':<{W_NAME}}{'Category':<{W_CAT}}"
f"{'Price':>{W_PRICE}}{'Lines':>{W_LINES}}{'Share':>{W_SHARE}}"
)
report.append("-" * WIDTH)
counts = []
names = []
for product_id, name, category, _cost, price, _launch in catalog_rows:
count = clean_products.count(name) # exact match with the official name
counts.append(count)
names.append(name)
report.append(
f"{product_id:<{W_ID}}{name:<{W_NAME}}{category:<{W_CAT}}"
f"{float(price):>{W_PRICE},.2f}{count:>{W_LINES}}"
f"{count / total_lines:>{W_SHARE}.1%}"
)
matched = sum(counts)
best = counts.index(max(counts))
report.append("-" * WIDTH)
report.append(
f"{'Total':<{W_ID + W_NAME + W_CAT + W_PRICE}}{matched:>{W_LINES},}"
f"{matched / total_lines:>{W_SHARE}.1%}"
)
report.append("=" * WIDTH)
report.append(f"Sales lines read: {total_lines:>6,}")
report.append(f"Product names cleaned: {messy:>6,}")
report.append(f"Lines matched to catalog: {matched:>6,}")
report.append(f"Lines not matched: {total_lines - matched:>6,}")
report.append(f"Most frequent product: {names[best]} ({counts[best]} lines)")
# --- Print and save ----------------------------------------------------------
text = "\n".join(report)
print(text)
REPORT_FILE.parent.mkdir(exist_ok=True)
REPORT_FILE.write_text(text + "\n", encoding="utf-8")
# --- Self-checks -------------------------------------------------------------
assert len(catalog_rows) == 30
assert matched == total_lines, "every clean name must be in the catalog"
assert REPORT_FILE.read_text(encoding="utf-8") == text + "\n"
Output
=============== Sales lines per product (sales_raw.csv) ===============
ID Product Category Price Lines Share
-----------------------------------------------------------------------
P001 Wireless Earbuds Electronics 79.99 91 7.6%
P002 Noise-Cancelling Headphones Electronics 249.00 45 3.8%
P003 55-inch 4K Smart TV Electronics 1,299.00 15 1.2%
P004 14-inch Ultrabook Laptop Electronics 1,149.00 32 2.7%
P005 Smartwatch Series 5 Electronics 199.99 54 4.5%
P006 Espresso Machine Home 349.00 31 2.6%
P007 Robot Vacuum Home 299.99 31 2.6%
P008 Chef's Knife Set Home 129.95 51 4.2%
P009 Air Purifier Home 189.00 46 3.8%
P010 Cotton Bed Sheet Set Home 69.99 62 5.2%
P011 Waterproof Rain Jacket Clothing 119.00 42 3.5%
P012 Merino Wool Sweater Clothing 89.50 31 2.6%
P013 Slim Fit Jeans Clothing 59.99 57 4.8%
P014 Running Socks 3-Pack Clothing 14.99 59 4.9%
P015 Organic Cotton T-Shirt Clothing 19.99 65 5.4%
P016 Trail Running Shoes Sports 129.99 38 3.2%
P017 Non-Slip Yoga Mat Sports 34.99 50 4.2%
P018 Adjustable Dumbbells Sports 279.00 22 1.8%
P019 Fitness Tracker Sports 99.99 36 3.0%
P020 2-Person Camping Tent Sports 189.99 20 1.7%
P021 Harbor Lane Mysteries Books 16.99 44 3.7%
P022 Weeknight Kitchen Cookbook Books 29.99 26 2.2%
P023 A Brief History of Maps Books 24.50 26 2.2%
P024 Statistics Made Simple Books 34.99 36 3.0%
P025 The Mindful Runner Books 14.99 9 0.8%
P026 Vitamin C Face Serum Beauty 24.99 36 3.0%
P027 Hydrating Face Cream Beauty 32.00 40 3.3%
P028 Shampoo and Conditioner Set Beauty 21.50 36 3.0%
P029 Electric Toothbrush Beauty 59.99 27 2.2%
P030 Mineral Sunscreen SPF 50 Beauty 15.99 42 3.5%
-----------------------------------------------------------------------
Total 1,200 100.0%
=======================================================================
Sales lines read: 1,200
Product names cleaned: 95
Lines matched to catalog: 1,200
Lines not matched: 0
Most frequent product: Wireless Earbuds (91 lines)

Run it from the project folder:

Terminal
python product_report.py

How it works:

  1. Settings. The paths and the six widths sit at the top. WIDTH is computed from the widths, so the title bar and the separators always match the table.
  2. Parsing. Each file is read into a text variable first, then csv.reader() gets its lines. csv.reader() splits each line at commas but keeps quoted fields together. split(",") would shift the columns of the 236 lines with a quoted date or price.
  3. Cleaning. " ".join(raw_name.split()) removes leading and trailing spaces and collapses double spaces. messy += raw_name != clean_name counts the changed names, because True is 1.
  4. Matching. The loop over the catalog unpacks each row into six names: for product_id, name, category, _cost, price, _launch in catalog_rows. Module 04 covers unpacking; a leading _ marks a value that the code does not use. clean_products.count(name) counts exact matches with the official spelling.
  5. Table. Each row uses the same nested specs as the header. Text columns align left, numbers right. {float(price):>{W_PRICE},.2f} converts the catalog price and formats it in one field.
  6. Summary. sum(counts) is 1,200, equal to the number of sales lines, so every cleaned name belongs to a real product. counts.index(max(counts)) finds the position of the largest count: Wireless Earbuds with 91 lines.
  7. Saving. The script prints the joined text and writes the same text with encoding="utf-8". The last assert reads the file back and compares, so a wrong encoding or a missing line would stop the script.

Alternative: module 04 replaces the 30 calls to count() with one pass over the sales lines and a dict of counters, which is much faster on big files. Module 25 does the whole report in pandas with df["product"].str.split().str.join(" ") and value_counts(). The cleaning rules stay the same.