Your assistant writes every question and every answer to the file chat.log. Logs are how you find out tomorrow what went wrong today. But customers put email addresses and phone numbers in their messages, and a log is read by developers, copied into log tools and kept for months. Personal data has no place in it.
The model still needs the real message to answer it; the log does not. So you mask each line just before it is written, in the one function every log line passes through.
You can't search for an email address the way you search for a word, because every address is different. What they share is a shape. A regular expression is a pattern that describes a shape, and re.sub(pattern, replacement, text) returns the text with every match replaced:
import re
text = "2 lamps and 14 mugs"
print(re.sub(r"\d+", "[n]", text)) # [n] lamps and [n] mugs
Here \d is one digit and + means "one or more". The r in front of the quote tells Python to leave the backslashes as they are.
Your finished program prints the log with the addresses and phone numbers masked, and everything else as it was:
question: Where is order 1042? Email me at [email] when it ships. answer: Order 1042 ships tomorrow, and I'll write to [email] when it leaves. question: The lamp arrived broken. Call me on [phone] or write to [email]. answer: Sorry about the lamp! We'll call you today on [phone]. question: Do you have 12 teapots in stock? My budget is $300. answer: Yes, 12 Teapots at $22 each come to $264.
Your task: make write_log pass each line through mask, define the patterns EMAIL and PHONE, and make mask replace every email address with [email] and every phone number with [phone].
Assignment
Follow the Coding Tutorial to mask email addresses and phone numbers in every line before it is written to the log.
Hint
Type the two patterns exactly as the tutorial shows them, with the r in front of the quote. mask needs one re.sub line per pattern, both above its return.
Free plan: 30 tutor messages. PRO is unlimited.
