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.
Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”Your script must:
- Read both files with
encoding="utf-8"and parse them withcsv.reader(). Skip the header rows. - Clean every product name in the sales file with
" ".join(name.split()). Count how many names changed. - For each of the 30 catalog products, count the sales lines whose clean name equals the official name exactly.
- Compute each product’s share of all sales lines, the total of matched lines and the most frequent product.
- 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. - Build the report as a list of lines, join them with
"\n", print the text and save it tooutput/product_report.txtwithencoding="utf-8". - End with
assertchecks: the catalog has 30 products, every sales line matched a product, and the saved file equals the printed text.
The expected report:
=============== 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,200Product names cleaned: 95Lines matched to catalog: 1,200Lines not matched: 0Most frequent product: Wireless Earbuds (91 lines)Step plan
Section titled “Step plan”-
Create the file. Make
product_report.pyin your project folder, next todata/. Add a comment at the top that says what the script does and which files it reads. -
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.
-
Read the files. Use
Path(...).read_text(encoding="utf-8").splitlines()and pass the lines tocsv.reader(). Wrap it inlist()and drop the header with[1:]. Printlen()of both lists once to check: 1,200 and 30. -
Clean the names. Loop over the sales rows. Clean column 7 and add it to a list. Add
raw != cleanto a counter;Truecounts as 1. Check that the counter is 95. -
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. -
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 withfloat()before you use:,.2f. -
Add the summary. Compute the matched total with
sum(counts)and the most frequent product withcounts.index(max(counts)). Append the five summary lines with a fixed label width. -
Print and save. Join the lines with
"\n", print the text, create theoutput/folder and write the file withencoding="utf-8". -
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: sales lines per product, from the raw export.import csvfrom 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 statementsRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- 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. - 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().) - Clean the
regioncolumn (index 4) too, and add a second small table with the lines per region and aMissingrow for"",N/Aand-. - Print the prices in European style (
1.299,00) withstr.maketrans()andtranslate(). - 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?
Reference solution
Section titled “Reference solution”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: clean the product names in data/sales_raw.csv and print# an aligned report of sales lines per product, checked against the catalog.
import csvfrom 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, 8WIDTH = 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 headercatalog_rows = list(csv.reader(catalog_text.splitlines()))[1:]
clean_products = []messy = 0for 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) == 30assert matched == total_lines, "every clean name must be in the catalog"assert REPORT_FILE.read_text(encoding="utf-8") == text + "\n"=============== 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,200Product names cleaned: 95Lines matched to catalog: 1,200Lines not matched: 0Most frequent product: Wireless Earbuds (91 lines)Run it from the project folder:
python product_report.pyHow it works:
- Settings. The paths and the six widths sit at the top.
WIDTHis computed from the widths, so the title bar and the separators always match the table. - 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. - Cleaning.
" ".join(raw_name.split())removes leading and trailing spaces and collapses double spaces.messy += raw_name != clean_namecounts the changed names, becauseTrueis 1. - 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. - 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. - 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. - 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.