# General Translation Python SDKs: 声明变量和变体 URL: https://generaltranslation.com/zh/docs/python/guides/declaring-variables.mdx --- title: 声明变量和变体 description: 如何在 Python 中使用 General Translation 的 declare_var、derive 和 decode_vars 保留动态值并生成有限的变体。 related: links: - /docs/python/guides/translating-strings - /docs/python/guides/detecting-locale - /docs/python/guides/configuring - /docs/python/guides/storing-translations --- 翻译后的字符串中,有些值本身不应该被翻译。Python SDK 为此提供了两个标记:[`declare_var`](/docs/python/reference/functions/declare-var) 用于真正动态的值,而 [`derive`](/docs/python/reference/functions/derive) 用于结果范围较小且固定的值。 ## 使用 `declare_var` 保留动态值 [#declare-var] 用 `declare_var` 包装运行时值 (例如用户名、电子邮箱地址或计数) ,这样它会嵌入消息中并按原样保留,而不会被翻译。它会返回一个 ICU `{_gt_, select, ...}` 结构,可放在 [`t`](/docs/python/reference/functions/t) 调用中。 ```python from gt_flask import t, declare_var t(f"Signed in as {declare_var(email, name='email')}") ``` 可选的 `name` 是变量的易读标签,便于翻译人员理解,也适用于 [`decode_vars`](/docs/python/reference/functions/decode-vars)。 ## 使用 `derive` 生成有限变体 [#derive] 当一句话中嵌入了一个取值范围小且固定的值时,只翻译一次是不够的——其他语言会根据每种结果对周围词语做不同的词形变化。`derive` 用来标记这类值,以便 CLI 为每个变体分别生成一条翻译。`derive` 在 运行时 时会原样返回输入值;在提取时,CLI 会为每种 outcome 生成一个 entry。 ```python from gt_flask import t, derive gender = "male" t(f"The {derive('boy' if gender == 'male' else 'girl')} is playing.") # 生成:"The boy is playing." 和 "The girl is playing." ``` 每个变体都会单独翻译,因此每个版本在各种语言中都能读起来自然流畅。 *注意:派生结果的集合应尽量保持精简。每增加一次 `derive` 调用,生成的条目数量都会成倍增加。* ## 结合两者 [#combine] 在派生句子中,你仍然可以使用 `declare_var` 嵌入真正的动态值,这样它就会被保留,而不会被翻译。 ```python from gt_flask import t, derive, declare_var t(f"{declare_var(name, name='name')} adopted a {derive('cat' if is_cat else 'dog')}.") ``` ## 使用 `decode_vars` 还原嵌入的值 [#decode] [`decode_vars`](/docs/python/reference/functions/decode-vars) 会将 字符串 中的 `{_gt_, select, other {value}}` 结构替换为其中嵌入的值——当你需要从带标记的 字符串 中还原出纯文本、已填充的 字符串 时,这个函数会很有用。 ```python from gt_i18n import declare_var, decode_vars marked = f"Signed in as {declare_var('a@b.com', name='email')}" decode_vars(marked) # "以 a@b.com 身份登录" ``` *注意:[`declare_static`](/docs/python/reference/functions/declare-static) 是 `derive` 的已弃用别名,出于向后兼容而保留。请在新代码中使用 `derive`。* ## Next steps - /docs/python/guides/translating-strings - /docs/python/guides/detecting-locale - /docs/python/guides/configuring - /docs/python/guides/storing-translations