Automating CSV Email Cleaning with Natural Language-Generated Scripts: An Engineering Practice
This article explains how to turn a plain-language request into a CSV email cleaning script and make its results reliable. It covers defining the input, rules, output, and error handling, designing the processing steps and statistics for reconciliation, choosing validation and deduplication rules, and verifying results through small-sample tests and reconciliation checks.
Automating CSV Email Cleaning with Natural Language-Driven Scripts: An Engineering Practice
1. The Problem: Engineering Issues Behind a Simple Request
Cleaning email addresses in a CSV file is a common data task that people often underestimate. On the surface, it only requires removing invalid emails, removing duplicates, and reporting the total. In practice, however, many details come up. Should leading and trailing spaces be trimmed? How should blank lines be handled? Are uppercase and lowercase versions duplicates? Do plus-sign aliases count as duplicates? Should invalid rows be logged with a reason? Should the output overwrite the original file? Does the total count match the number of output rows? Will repeated runs produce the same result?
Natural language-driven script generation lowers the barrier to entry. Users describe their needs in everyday language, and an AI coding tool produces a script that can run after it is copied. This shortens the path from idea to result. However, it does not mean you can skip requirement clarification or result verification. Low barrier does not mean low risk. If the request is vague, the script may apply an inappropriate deduplication rule or silently skip abnormal data, which makes the results impossible to audit.
A more reliable approach is to treat the natural language description as a requirement input and the generated script as a first draft. You then complete the engineering loop by defining clear input and output contracts, rules, error handling, statistical fields, and acceptance criteria.
2. Requirements: Writing a Natural Language Description as an Executable Contract
To get a reliable script from an AI coding tool, the request should cover five elements: input, rules, output, error handling, and acceptance criteria.
A fairly complete natural language request might look like this:
I have a CSV file with a column named email. Please read the file and clean the email column. Trim leading and trailing whitespace. Skip empty values. Use a general email format rule to determine whether each address is valid. Deduplicate valid emails based on their normalized value. Output a file named cleaned_emails.csv that contains only one column, email. Also output statistics, including the total number of rows, the number of empty values, the number of invalid entries, the number of duplicates, and the number of unique valid emails. If a row cannot be parsed, record its line number and the reason. Repeated runs should produce consistent results.
This description is closer to an executable contract than a request like “clean up my emails.” It specifies the column name, the output file, the statistical definitions, and how errors are recorded. In practice, you can also specify the file encoding, delimiter, whether original line numbers are kept, whether the output file may be overwritten, whether the local part of an address should be lowercased, and whether plus-sign aliases count as duplicates.
3. Script Logic: Reading, Validating, Normalizing, Deduplicating, and Writing Output
A clear processing pipeline usually includes the following steps:
- Read the input file and identify the header and the target column.
- Read the rows one by one and count the total number of rows.
- Trim leading and trailing whitespace from each email field.
- Count empty values separately and skip them.
- Validate each address against the email format rule.
- Normalize valid addresses to produce a deduplication key.
- Use a set or hash structure to detect duplicates.
- Write the first occurrence of each unique valid email to the output file.
- Aggregate the statistics and print them.
- Record the line numbers and reasons for invalid rows so they can be reviewed.
Here is a pseudocode example:
input_path = "emails.csv"output_path = "cleaned_emails.csv"seen = empty_set()stats = {total: 0, empty: 0, invalid: 0, duplicate: 0, valid_unique: 0}for row in read_csv(input_path):stats.total += 1raw = trim(row["email"])if raw == "":stats.empty += 1continueif not is_valid_email(raw):stats.invalid += 1log_invalid(row.line_number, raw, "invalid_format")continuekey = normalize_email(raw)if key in seen:stats.duplicate += 1continueseen.add(key)write_line(output_path, key)stats.valid_unique = size(seen)print(stats)
The key point of this pseudocode is the order of processing and the statistical definitions, not the specific language. The statistics should be complete. A single total is not enough, because you cannot reconcile the results without the breakdown. At minimum, keep five metrics: total rows, empty values, invalid entries, duplicates, and unique valid emails. Make sure the unique valid count matches the number of rows in the output file.
4. Validation Rules and Deduplication Logic: Define the Business Requirements First
Email validation should not aim for complete theoretical coverage. Instead, choose rules that match the business risk. A general format rule can be expressed as:
^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
This rule works well as a basic filter, but it does not handle every edge case. In real projects, you need to decide whether internationalized domain names are allowed, which special characters are accepted, whether domains without a dot are valid, and whether strings with display names are accepted. If the input comes from user entry, start with a conservative filter, record invalid samples, and adjust the rule based on those samples. Do not start with overly complex validation logic.
Deduplication logic depends even more on business decisions. Common normalization steps include trimming whitespace and converting the domain part to lowercase. Lowercasing the local part requires care. In theory, the local part may be case-sensitive, but most business scenarios lowercase it to reduce duplicates. Whether plus-sign aliases or dot variants count as the same address must be decided by the business. For example, user+tag@example.com and user@example.com may be duplicates for one business and distinct addresses for another. Put the normalization logic in a separate function so you can change the rules without affecting the main workflow.
5. Error Handling and Engineering for Production
A data cleaning script must handle errors and be maintainable if it will be used over time. At the file level, plan how to handle inconsistent encodings, changed delimiters, missing target columns, empty files, unwritable output paths, and existing output files. At the data level, record the line number and reason for every row that cannot be parsed. Sample invalid emails and redact sensitive parts before logging them. Write the statistics to a log or a separate result file.
When deploying in the cloud, you can use general cloud services to run the batch process. For example, in a Baidu AI Cloud environment, you could store the source and result files in object storage, record statistics and errors with a log service, and run the cleaning task on a container platform. Confirm specific APIs, quotas, and pricing in the official product documentation. Regardless of the deployment method, write results to a temporary file first, then atomically replace the output file after validation passes. This prevents incomplete result files when a run fails midway. Repeated runs should also be idempotent, so the same input always produces the same output.
6. Verification and Delivery: Building Trust Through Reconciliation and Sampling
Do not run the script on the full dataset right away after generating it. First, build a small test set that covers normal emails, empty values, leading and trailing spaces, duplicates, case differences, obviously invalid formats, blank lines, and missing columns. After the test run, check three things: whether the number of output rows equals the unique valid count, whether the total count equals the sum of all categories, and whether repeated runs produce the same result.
For the full run, perform sampling checks and reconciliation. Reconciliation includes checking that the total input rows equal the sum of the statistical categories, that the output row count equals the unique valid count, and that the number of error log entries matches the invalid count. If the numbers do not match, first check whether empty values, parsing failures, and write failures were counted correctly.
7. Practical Checklist
- Describe requirements using five elements: input, rules, output, errors, and acceptance criteria.
- Separate email validation and deduplication normalization into independent functions.
- Keep the statistics complete so they can be reconciled with the output file.
- Record line numbers and reasons for error rows, and redact sensitive data.
- Use a temporary file and atomic replacement for output, and make the script safe to run repeatedly.
- Validate with a small sample before running the full dataset.
- Keep script versions, run logs, and statistical results for auditing and reproduction.
Natural language generation helps you quickly handle repetitive data cleaning work. However, the quality of the results still depends on clear requirement contracts, explicit rules, reconcilable statistics, and traceable errors. Once these engineering details are in place, a low-barrier tool can become a stable and reusable data governance capability.
