import type { Node, Translator } from '../contract' import { insideAnnotation, pythonTokenRole } from '../languages/python' import { createZhTemplateTranslator } from './zhTemplate' function stringContent(node: Node): string { if (node.type === 'string_content') return node.text return node.children.map(child => child ? stringContent(child) : '').join('') } /** `#` 注释去掉井号;docstring 只取引号里的内容。 */ function commentText(node: Node): string { return node.type === 'comment' ? node.text.replace(/^#+\s?/, '') : stringContent(node) } export const pythonZhTranslator: Translator = createZhTemplateTranslator({ id: 'python.zh-template', label: '中文直译', languageIds: ['python'], tokenRole: pythonTokenRole, keywords: { 'import': '导入', 'from': { zh: '从', byContext: { raise_statement: '源自', yield: '自' } }, 'as': '作为', 'def': '函数', 'async': '异步', 'await': '等待', 'class': '类', 'return': '返回', 'if': '如果', 'elif': '否则如果', // 循环的 else 只在没被 break 打断时执行,try 的 else 只在没抛异常时执行 'else': { zh: '否则', byContext: { 'for_statement > else_clause': '未中断时', 'while_statement > else_clause': '未中断时', 'try_statement > else_clause': '未出错时', }, }, 'for': '遍历', 'in': { zh: '在', byContext: { for_statement: '取自', for_in_clause: '取自' } }, 'while': '当', 'try': '尝试', 'except': '捕获', 'finally': '最终', 'raise': '抛出', 'with': '使用', 'yield': '产出', 'lambda': '匿名函数', 'pass': '跳过', 'break': '跳出', 'continue': '继续', 'global': '全局', 'nonlocal': '非局部', 'del': '删除', 'assert': '断言', 'not': '非', 'and': '与', 'or': '或', 'is': '是', 'not in': '不在', 'is not': '不是', 'match': '匹配', 'case': '情况', }, literals: { none: '空', true: '真', false: '假' }, builtinTypes: { str: '字符串', int: '整数', float: '浮点数', bool: '布尔', list: '列表', dict: '字典', set: '集合', tuple: '元组', bytes: '字节串', }, isTypePosition: leaf => leaf.type === 'identifier' && leaf.parent?.type !== 'attribute' && insideAnnotation(leaf), operators: { '==': '等于', '!=': '不等于' }, operatorParents: ['comparison_operator'], emptyLiterals: { list: '空列表', dictionary: '空字典' }, stringNodes: ['string'], commentText, })