阅读文本 / Reading text
This paper uses synthetic samples to demonstrate the processing method. The code has been verified using examples in an isolated environment; this does not guarantee effectiveness for all real-world files or products. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document.
“Welcome, {name}” After being translated into another language, the variable names are translated along with it, and the page typically only reports an error when the actual values are filled in. An earlier checkpoint occurs during translation delivery: extract the fields from the format string, verify their identities, occurrence counts, and format specifications, rather than merely counting the curly braces.
first selects the format grammar
below only processes Python
str.format
style, without overriding JavaScript templates, ICU MessageFormat, or other placeholder systems. Nested structures, escaping rules, and pluralization conventions vary across systems; no single regular expression can claim to support them all. The example explicitly requires named fields and rejects automatically numbered fields.
The escaped curly braces are not variables.
{{name}}
denotes the displayed text
{name}
, should not be counted as a field. Format specifications may also contain nested fields, for example
{value:{width}}
. Below, the specifications are read recursively, and duplicate occurrences of the same field are retained with a count.
from string import Formatter
from collections import Counter
def contract(text, depth=0):
if depth > 5:
raise ValueError("nested format budget")
result = Counter()
for literal, field, spec, conversion in Formatter().parse(text):
if field is None:
continue
if not field or field != field.strip():
raise ValueError("named field without surrounding whitespace required")
result[(field, conversion, spec)] += 1
if spec:
result.update(contract(spec, depth + 1))
return result
assert contract("Hi {name}, total {amount:.2f}") == contract("{name}:金额 {amount:.2f}")
assert contract("{{name}}") == Counter()
assert contract("{name} {name}") != contract("{name}")
assert contract("{value:{width}}")[("width", None, "")] == 1
assert contract("{amount:.2f}") != contract("{amount:.0f}")
for bad in ["Hi {name", "{ name}", "{}"]:
try:
contract(bad)
except ValueError:
pass
else:
raise AssertionError("invalid template accepted")
This contract is deliberately made more stringent
Here, format specifications are also treated as protected content; therefore, changes to the number of decimal places will be flagged. Certain localization tasks do indeed require modifications to numerical formatting, so a separate rule should be established for this purpose rather than disabling all placeholder checks. The nesting depth limit is an example budget, not a requirement of the language specification.
change
This example's result
proofreading action
field repositioned
accepts
Is the reading order natural
appears one fewer time in the same field than
rejects the contract
Check for any omitted translations.
variable name was translated
rejects the contract
recovery interface field name
Decimal format change
tag inconsistency
Confirmed according to the localization protocol
does not execute untrusted templates
This code segment only parses; it does not actually invoke
format
is the input object. It is also not a template-safe sandbox. Subsequent rendering must further restrict available fields, object access, and output contexts, particularly the escaping rules in HTML pages.
Leave a check between translation and deployment
uses
OmniDoc (product entry point)
When processing materials containing template content, first list which fields must remain unchanged. After translation, perform structural checks and linguistic proofreading separately: a sentence that reads smoothly does not necessarily prove that the variable contracts are still valid.
Reference:
Python string and Formatter
。
- 1 -
Updated 2026-10-08