如何用JavaScript提取Python类的注解与参数列表(不使用正则)
不使用正则表达式提取Python类注解及参数列表的方法
可以不用正则表达式实现这个需求,核心思路是通过逐行解析文本定位类的文档注释和参数,步骤如下:
- 先将文件内容按行分割为数组,遍历找到类定义行(比如包含
class MyClass():的行) - 在类定义行之后,定位以
"""开头的文档注释起始位置,继续遍历直到找到结束的""" - 提取注释块内的有效内容,按行拆分后过滤空行,再对每行按固定格式拆分出参数名、类型和描述
下面是具体的JavaScript实现示例:
// 假设fileContent是读取到的myfile.py文件内容 function extractClassInfo(fileContent) { const lines = fileContent.split('\n').map(line => line.trim()); let inDocstring = false; let docstringLines = []; let foundClass = false; for (const line of lines) { // 定位类定义行 if (line.startsWith('class ') && line.endsWith(':')) { foundClass = true; continue; } // 找到类后处理文档注释 if (foundClass) { if (line.includes('"""')) { if (inDocstring) { // 注释块结束,退出遍历 break; } else { inDocstring = true; // 移除开头的"""并保留有效内容 const content = line.replace(/^"""/, '').trim(); if (content) docstringLines.push(content); } } else if (inDocstring) { docstringLines.push(line); } } } // 解析参数列表 const params = docstringLines.map(line => { const [typePart, desc] = line.split(' - '); const [name, type] = typePart.split(': '); return { name, type, description: desc }; }); return { docstring: docstringLines.join('\n'), parameters: params }; } // 使用示例 const fileContent = `class MyClass(): """ a: string - parameter a """`; const result = extractClassInfo(fileContent); console.log(result);
这种方法依赖Python代码的格式规范(比如文档注释用三重引号、参数注释格式统一),如果代码格式有变动,只需调整对应判断逻辑即可,全程无需正则表达式匹配复杂模式。
内容的提问来源于stack exchange,提问作者Vetedde
相关产品推荐
相关产品推荐

