본문으로 건너뛰기

P6 — Text Processing in Python

About 55 min

Before L4.1 — Text Is Not Numbers Yet, read strings and regex patterns used by the L4.1, L4.2, L4.3, L4.7, and L4.13 Lab starters. P3 teaches writing functions and loops. If you get every question below right, you can move to the next lesson. This optional guide, its diagnostic, and its Lab do not count toward course progress.

Quick Check

1. What does 'Cats'.lower() produce?
2. What does re.findall(r'[a-z]+', 'cat 42 dog') return?
3. What does Counter(['a','a','b'])['a'] equal?
4. Can one Unicode character require more than one UTF-8 byte?

0 of 4 questions answered.

Goal

Use string operations, a small regular expression, dict/set and Counter to trace text → tokens → counts → token IDs. Distinguish Unicode characters from encoded bytes.

Strings are sequences, not tokens yet​

text = " Cats nap. "
clean = text.strip().lower() # "cats nap."
words = clean.split() # ["cats", "nap."]
joined = " ".join(words) # "cats nap."
pieces = clean.replace(".", " .").split()

.strip() removes surrounding whitespace; .lower() normalizes case; .split() breaks on whitespace; .replace(old,new) returns a changed copy; .join(...) combines strings. These choices define the tokenizer contract. Python strings are immutable; lower() does not change the original text unless you assign its result.

Regex is a compact matching rule​

import re
text = "Cats nap. Cats play!"
tokens = re.findall(r"[a-z]+|[.!?]", text.lower())
# ["cats", "nap", ".", "cats", "play", "!"]

r"..." is a raw string, useful because regular expressions contain backslashes. [a-z]+ means one or more lowercase letters; | means or; [.!?] matches one of three punctuation symbols. re.findall returns non-overlapping matches. Unlike split(), this pattern captures punctuation as separate tokens. It is intentionally English-only; it drops digits, accents and other scripts. Do not present it as a multilingual production tokenizer.

Other patterns you will encounter in L4 starters: re.sub(pattern, replacement, text) substitutes matches, \s+ matches runs of whitespace, and re.escape(text) treats dynamic text literally. Always test a regex against an example it could mishandle.

Dict, set, and Counter​

from collections import Counter
counts = Counter(tokens) # 'cats' occurs twice
unique = set(tokens) # membership, no guaranteed learning order
vocab = {piece: i for i, piece in enumerate(sorted(unique), start=1)}
ids = [vocab[piece] for piece in tokens]

A dict maps keys to values, a set keeps unique values, and Counter behaves like a dict of frequencies. sorted(set(...)) makes the initial IDs deterministic; enumerate(..., start=1) reserves 0 for a chosen special-token policy. Using vocab.get(piece, 0) lets a later example map unknown pieces to the reserved ID. Sorting is a design choice, not an inherent meaning of token IDs.

Unicode and bytes​

word = "한"
encoded = word.encode("utf-8") # 3 bytes, not one ASCII byte
assert encoded.decode("utf-8") == word
print(len(word), len(encoded)) # 1 3

Characters are Unicode text; UTF-8 is a byte representation. len(text) counts Python code points, not always user-perceived characters, and len(encoded) counts bytes. Errors arise when decoding with the wrong encoding. L4.5 discusses byte-level tokenization. In L4.13 use non-English and punctuation cases to catch limitations.

Predict

What does re.findall(r'[a-z]+', 'Café!'.lower()) miss?

Guided browser Lab​

Complete the three pure-Python TODO functions: matching lowercase words and punctuation, counting tokens, and assigning deterministic vocabulary IDs. Use the test failures to check repeated tokens, empty input, and stable order. Then try the string “Hi 42!”: describe precisely which characters the sample regex discards.

Loading lab…

Quick Check

1. What does re.findall(r'[a-z]+','Hi 42!'.lower()) return?
2. What is Counter(['red','blue','red','red'])['red']?
3. How can a vocabulary get deterministic IDs regardless of token arrival order?
4. Why might len('한'.encode('utf-8')) exceed len('한')?

0 of 4 questions answered.

Key Takeaways

  • String methods and regex express different, explicit splitting rules.
  • Sets remove duplicates; Counter retains counts; a sorted dict construction gives stable IDs.
  • Unicode characters are not the same unit as UTF-8 bytes; this sample regex is not multilingual.