替换python docstrings

2024-06-16 13:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个epytext到{a2}的标记转换器,现在我想将整个库中的所有docstring从epytext转换为reST格式。在

有没有一种聪明的方法可以读取模块中的所有docstring并写回替换的内容?在

可能是ast模块?在


Tags: 模块方法标记resta2内容格式ast
3条回答

也许最直接的方法就是用传统的方法。这里有一些初始代码可以帮助你。它可能更漂亮,但应该给出一个基本的想法:

def is_docstr_bound(line):
    return "'''" in line or  '"""' in line

# XXX: output using the same name to some other folder
output = open('output.py', 'w')

docstr_found = False
docstr = list()
with open('input.py') as f:
    for line in f.readlines():
        if docstr_found:
            if is_docstr_bound(line):
                # XXX: do conversion now
                # ...

                # and write to output
                output.write(''.join(docstr))

                output.write(line)

                docstr = list()
                docstr_found = False
            else:
                docstr.append(line)
        else:
            if is_docstr_bound(line):
                docstr_found = True

            output.write(line)

output.close()

要使其真正起作用,您需要将其与文件查找程序连接起来,并将文件输出到其他目录。查看os.path模块以供参考。在

我知道docstring绑定检查可能非常弱。最好稍微加强一点(剥离行并检查它是否以docstring绑定开始或结束)。在

希望能给一些想法。也许有更优雅的方法来处理这个问题。:)

Pyment是一个工具,可以转换Python docstring并创建缺少的一个骨架。它可以管理GoogleEpydoc(javadoc样式)、NumpydocRestructedText(reST,Sphinx默认)docstring格式。在

它接受单个文件或文件夹(也可以浏览子文件夹)。对于每个文件,它将识别每个docstring格式并将其转换为所需的格式。最后,将生成一个补丁来应用于该文件。在

要转换项目:

  • 安装Pyment

键入以下内容(可以使用virtualenv):

$ git clone https://github.com/dadadel/pyment.git
$ cd pyment
$ python setup.py install
  • 从Epydoc转换为Sphinx

通过执行以下操作,可以将项目转换为Sphinx格式(reST),这是默认的输出格式:

^{pr2}$

编辑:

使用pip安装:

$ pip install git+https://github.com/dadadel/pyment.git

对于这种简单的用法来说,这可能是一种过激的做法,但我会考虑使用2to3的机制来进行编辑。只需要写一个定制的修复程序。它没有很好的文档,但是开发人员指南python3.0:python2.6和从2迁移到3:More about 2to3Implement Custom Fixers提供了足够的详细信息来开始。。。在

Epydoc似乎包含一个^{}方法,它可能有助于实际翻译docstring。不知道有没有什么好处。。。在

相关问题 更多 >