Optional
Check text and token coordinates
Inspect the full fictional inputs, rerun the standard-library calculations, and check the stated invariants. Optional desktop practice.
- Version
- v2
- Minutes
- ~15
- Evidence
- Self-check in the notebook
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
Text as data / Текст как данные
Optional practice. The lesson and its phone questions are complete without running code. / Необязательная практика: урок и задания на телефоне самостоятельны.
All inputs and calculations were authored for the Fedor Pakhurov project with Codex assistance. The example is fictional and contains no external corpus, model, or copied third-party implementation. Selected first-party functions are retained from the published reviewed fixture. This notebook adds packaging and explicit self-checks; it does not claim operational quality.
Все входы вымышлены; расчёты созданы для проекта Фёдора Пахурова с помощью Codex. Внешних корпусов, моделей и сторонних реализаций здесь нет. Функции взяты из указанной опубликованной проверенной версии; добавлены оформление и самопроверки.
Saved outputs use Python 3.9.7; standard library only, no network or file writes. Floating last digits and Unicode database values can differ across runtimes. / Сохранённый запуск: Python 3.9.7, только стандартная библиотека, без сети и записи файлов. Последние разряды и версия Unicode могут зависеть от среды.
import json
import math
import re
import unicodedata
from collections import Counter
from fractions import Fraction
def text_data():
composed = "réglage L7"
decomposed = "re\u0301glage L7"
normalized = unicodedata.normalize("NFC", decomposed)
assert normalized == composed and decomposed != composed
assert unicodedata.normalize("NFC", normalized) == normalized
raw = "lamp L7: not ready!"
standardized = unicodedata.normalize("NFKC", raw).casefold()
matches = [(m.group(), m.start(), m.end()) for m in re.finditer(r"\w+|[^\w\s]", standardized)]
assert all(standardized[a:b] == word for word, a, b in matches)
# Offsets address the normalized string; this fixture does not claim raw alignment.
removed_not = " ".join(w for w, _, _ in matches if w not in {"not", ":", "!"})
assert removed_not == "lamp l7 ready"
labels = ["Lamp", "lamp", "Lamp", "lamp!", "lamps"]
stages = [labels, [unicodedata.normalize("NFKC", s) for s in labels]]
stages.append([s.casefold() for s in stages[-1]])
stages.append([re.sub(r"[^\w\s]", "", s) for s in stages[-1]])
assert [len(set(stage)) for stage in stages] == [5, 4, 3, 2]
return {"unicode_database": unicodedata.unidata_version,
"composed": {"text": composed, "code_points": len(composed), "utf8_bytes": len(composed.encode())},
"decomposed": {"text": decomposed, "code_points": len(decomposed), "utf8_bytes": len(decomposed.encode())},
"nfc_equal": normalized == composed, "raw": raw, "normalized": standardized,
"normalized_offsets": matches, "destructive_stopword_result": removed_not,
"type_counts_by_stage": [len(set(stage)) for stage in stages]}
result = text_data()
print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
assert result['type_counts_by_stage'] == [5, 4, 3, 2]
for token, start, end in result['normalized_offsets']:
assert result['normalized'][start:end] == token
assert result['nfc_equal']
print('All local checks passed; this is a constructed example, not a benchmark.')