Translating Tech Docs Without Translating the Code

puts userid is translated as “user identifier,” or <div class="container"> Localizing the class attribute in [ ] is the most costly and hardest-to-diagnose erro

Technical documents mix prose with code, and a translation tool that doesn't tell them apart can change identifiers, tags and attribute values. This guide is for documentation writers, localization engineers and developers who translate HTML documentation and need the code to survive intact.

The core problem is that a translation engine may rewrite user_id as “user identifier” or alter <div class="container">. These changes rarely crash the program. They do break copied examples and make API documentation unusable, and they are hard to spot in review.

The fix lies less in how capable the translation engine is and more in whether preprocessing can separate natural language from machine language within the DOM tree. You will see why regular expressions fall short, how a parser such as Beautiful Soup handles nested markup, and how to check the result against clear acceptance criteria.

How do you translate tech docs without changing the code? The short answer

Isolate code nodes in the DOM tree before translation, then check the output against an acceptance table.

Your situationWhat to doWhy
Your HTML contains <code>, <pre> or <kbd> tagsTraverse the DOM with a parser and mask those nodes before translationNode traversal targets elements directly, whatever their internal structure
Your code sits inside links or formatting tagsUse get_text() or recursive traversal, and lock attribute values such as hrefcode.string returns None when the content is in a child node, and a whole-tag translation can corrupt URLs
Your docs use custom containers such as <div class="code-snippet">Add a CSS class whitelistThese are not standard semantic tags, so they would otherwise be translated as ordinary paragraphs
Your documents are plain Markdown, compressed single-line HTML or lack semantic tagsClean up the formatting first or hand them to human reviewersThe parser may fail to find code boundaries
You are unsure whether protected code survivedRun the checks in the acceptance table and review flagged items manuallyAutomated checks cover structure, but not every case

Why translation errors in code are costly

Localizing the class attribute inside [ ] is one of the costliest errors in technical documentation translation, and one of the hardest to diagnose. Such errors usually do not crash the program. Instead, they cause:

  • Copied and pasted code that throws errors
  • API documentation examples that cannot run at all
  • Identifiers and attribute values that look plausible, so reviewers miss them

Why regular expressions cannot protect code

Many teams try to replace code snippets with regular expressions before translation. This works poorly on HTML, because HTML is not linear text. It is a nested tree.

  • A <code> tag may contain a <span> for highlighting.
  • A <code> tag may sit inside an <a> tag that forms a link.
  • Regular expressions cannot follow this nesting, so they often break tag pairs or miss boundary cases.

Using a parser to protect code nodes

A parser such as Beautiful Soup moves code protection from string matching to node traversal. According to the official documentation for Beautiful Soup 4.15.0, you work directly with Tag objects in the DOM tree instead of searching for character patterns.

To find the regions to mask:

  1. Identify semantic tags such as pre, code, kbd and samp.
  2. Identify elements with specific classes, such as highlight or language-python.
  3. Mask those regions, however complex their internal structure.

Test cases: correct output and boundary traps

To verify the protection logic, build a set of well-defined synthetic test cases. The inputs below only demonstrate the parsing logic.

Synthetic input HTML:

<p>请运行 <code class="cmd">pip install -r requirements.txt</code> 来安装依赖。</p>
<pre><code># 初始化配置
config = {"timeout": 30}</code></pre>
<p>注意:<var>timeout</var> 参数单位为秒。</p>

Expected extraction result: The translation system should receive only the following plain-text paragraphs. Code sections are either replaced by placeholders or stripped out completely.

  1. "Please run [CODE_0] to install dependencies."
  2. "Note: The unit of the [VAR_0] parameter is seconds."

The content of a <pre> block must not appear in the text stream to be translated. Alternatively, it must remain unchanged at the byte level on export.

Typical errors and boundary inputs

  • Nested tags: In <code><b>bold_code</b></code>, extracting only code.string returns None, because the text sits in the child node b. Use get_text() or traverse descendants recursively.
  • Attribute value leakage: In <a href="/api/v1/users">用户接口</a>, only the link text should be translated, to “user interface”. Lock the href value. If the whole tag is converted to a string and passed to the translator, the URL may be corrupted.
  • Pseudocode tags: <div class="code-snippet"> is not a standard semantic tag. Capture it through a CSS class name whitelist, or it will be translated as an ordinary paragraph.

Identifying code nodes in the DOM tree

The Python example below shows how to traverse the document tree with Beautiful Soup and separate translatable text from protected code. It is an in-memory demonstration only. It makes no network requests, runs no shell commands and writes no files. Run it in an environment with beautifulsoup4>=4.15.0.

from bs4 import BeautifulSoup, NavigableString, Tag

# 合成示例:包含内联代码、代码块及普通文本(仅用于演示,非真实数据)
HTML_SAMPLE = """
<article>
  <p>使用 <code class="cli">kubectl get pods</code> 查看状态。</p>
  <pre><code>def hello():
    print("Hello World")</code></pre>
  <p>返回值 <var>result</var> 可能为空。</p>
</article>
"""

# 定义需要整体保护的标签集合
PROTECTED_TAGS = {'pre', 'code', 'kbd', 'samp', 'var'}

def extract_translatable_segments(html_content: str) -> list[dict]:
    """
    提取HTML中的文本片段并标记是否可翻译。
    注意:此为教学演示代码,生产环境需增加占位符生成与属性保护逻辑。
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    segments = []

    # 遍历所有文本节点,而非仅顶层标签
    for element in soup.descendants:
        if isinstance(element, NavigableString):
            # 检查父链上是否存在受保护标签
            parent_chain = list(element.parents)
            is_protected = any(
                p.name in PROTECTED_TAGS
                for p in parent_chain
                if isinstance(p, Tag)
            )

            text = str(element).strip()
            if not text:
                continue

            segments.append({
                'text': text,
                'translatable': not is_protected,
                'context': element.parent.name if element.parent else 'root'
            })
    return segments

# 执行提取并断言预期行为
results = extract_translatable_segments(HTML_SAMPLE)
translatable_texts = [s['text'] for s in results if s['translatable']]
protected_texts = [s['text'] for s in results if not s['translatable']]

# 验证:普通文本应被标记为可翻译
assert any('查看状态' in t for t in translatable_texts), "普通文本未被识别"
# 验证:代码内容不应出现在可翻译列表中
assert not any('kubectl' in t for t in translatable_texts), "内联代码泄露至翻译区"
assert not any('print' in t for t in translatable_texts), "代码块内容泄露至翻译区"
# 验证:受保护内容被正确归类
assert any('kubectl' in t for t in protected_texts), "内联代码未被保护"

print(f"可翻译片段数: {len(translatable_texts)}")
print(f"受保护片段数: {len(protected_texts)}")

The key step is the chained check on element.parents. Even when a <code> element is nested inside a <p>, its text nodes are still marked as non-translatable. This script only demonstrates extraction and validation. It is not a complete translation and replacement system. In production you must also handle placeholder backfilling and attribute protection.

Acceptance criteria and manual review

Passing without errors does not prove that code protection worked. Use the table below during delivery. It lists automated checks and the cases that need manual review.

Check itemAutomated verification methodManual review triggerProcessing decision
Tag integrityCompares the hash of the DOM tree structure before and after translationTranslation contains unclosed or improperly nested tagsRefuse delivery and reprocess from the original text
Attribute value retentionUses a regular expression check to confirm key attributes (href, src, id) are unchangedDynamic URL with path parameters or a query stringFlag as high risk for developer confirmation
Placeholder restorationChecks that the number of placeholders in the translation matches the originalPlaceholder position does not fit the target language syntaxReorder the sentence, splitting it into separate sentences if needed
Pseudocode recognitionChecks the class whitelist hit rateCustom component or non-standard code containerAdd supplementary rules or annotate manually
Comment translationChecks whether comments inside code blocks were skippedComments explain important business logicExtract the comment and translate it separately

Scope of this checklist: The automated validation applies only to well-structured HTML with semantic markup. Plain text from Markdown rendering that lacks semantic tags, <div> and <span> code blocks, and compressed single-line HTML may not let the parser find code boundaries. Clean up the formatting of such documents first, or have a human reviewer handle them. This validation also only confirms that code was not translated. It does not guarantee the quality of the translated prose.

📊 At a glance

ApproachHow it worksHandles nested tagsSuited to
Regular expressionsMatches character patterns in the textNo. Tag pairs can break and boundary cases are easy to missSimple, flat text with no nesting
DOM parser (Beautiful Soup)Traverses Tag objects and masks matching elementsYes. Matches elements whatever their internal structureHTML documentation with <code>, <pre>, links and custom containers

🎯 Which approach fits you?

If you translate HTML docs with code inside links or formatting tags

Use a DOM parser, and read text with get_text() or recursive traversal so the child nodes are included.

If your docs use custom code containers

Add a CSS class whitelist, then check the pseudocode recognition row of the acceptance table.

If your files are plain Markdown or compressed single-line HTML

Clean up the formatting first, or send them to a human reviewer, because automated boundary detection may fail.

Resources and next steps

Applying this checklist to document translation

Treat the body text, links, code and structure of a web document as separate parts. Add the protected sections to your acceptance checklist, then assess how readable and well presented the translated content is.

OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.

❓ FAQ

1. Why can't I just use regular expressions to protect code in HTML?

HTML is a nested tree, not linear text. Regular expressions cannot follow nested tags, so they often break tag pairs or miss boundary cases.

2. What does a parser like Beautiful Soup do differently?

It works on Tag objects in the DOM tree. You identify elements such as pre, code, kbd and samp, plus classes such as highlight, and mask them, however complex their internal structure.

3. Why does code.string sometimes return None?

When the content sits in a child node, such as <code><b>bold_code</b></code>, code.string returns None. Use get_text() or traverse the descendants.

4. Does passing these checks guarantee a good translation?

No. The checks confirm that code was not translated and that structure and attributes survived. They do not assess the quality of the translated natural language.

📝 Summary

Protect code by isolating it in the DOM tree before translation, not by matching patterns in text. Check the result with the acceptance table, and send anything that falls outside its scope to manual review.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29