Programming for Data Processing

Lectures: Nguyễn Tuấn Phong, Đào Việt Anh

Labs: Trịnh Ngọc Huỳnh, Phạm Tiến Du

Semester: 2025-2026-1

Institute for AI, VNU-UET

Lecture 10
Part 1:
String Manipulation

Why strings matter

  • Clean & canonicalize messy text
  • Extract structure (emails, URLs, phones)
  • Inputs for joins, features, and QA checks

Bytes vs text (encodings)

  • Files: bytes
  • Python: Unicode str
  • Specify encoding="utf-8"
  • Use errors="replace" at ingestion

Unicode normalization & casefold

  • NFKC unifies full-width/compat forms
  • casefold() > lower() for matching
  • Diacritics: strip only when appropriate

Idempotent cleaner

  • Order: normalize → casefold → trim → collapse
  • Idempotent: re-running changes nothing
  • Avoid lossy steps too early

Regex essentials

  • Named groups, flags, non-greedy .*?
  • Pre-compile for reuse
  • Prefer libraries for complex URLs/HTML

Vectorized Pandas string ops

  • .str.extract, .str.contains, .str.replace
  • regex=False for literals; set na= explicitly
  • Reuse compiled patterns

Parsing semi-structured

  • JSONL: stream line-by-line
  • Logs: small regex with groups
  • Use parsers for HTML

PII redaction & ethics

  • Redact emails/phones early
  • Log changes; keep an audit trail
  • Preserve meaning; document assumptions