相关疑难解决方法(0)

从Python源代码中提取注释

我正在尝试编写一个程序来提取用户输入的代码中的注释.我试图使用正则表达式,但发现很难写.

然后我在这里找到了一个帖子.答案建议用来tokenize.generate_tokens分析语法,但文档说:

所述generate_tokens()发电机需要一个参数,readline,它必须是一个可调用的对象,它提供了相同的接口 readline()的方法内置的文件对象(见文件对象).

但是字符串对象没有readline方法.

然后我在这里发现了另一篇文章,建议StringIO.StringIO用来获取readline方法.所以我写了下面的代码:

import tokenize
import io
import StringIO

def extract(code):
    res = []
    comment = None
    stringio = StringIO.StringIO(code)
    for toktype, tokval, begin, end, line in tokenize.generate_tokens(stringio):
        # print(toknum,tokval)
        if toktype != tokenize.COMMENT:
            res.append((toktype, tokval))
        else:
            print tokenize.untokenize(toktype)
    return tokenize.untokenize(res)
Run Code Online (Sandbox Code Playgroud)

并输入以下代码: extract('a = 1+2#A Comment')

但得到了:

Traceback (most recent call last):     
   File "<stdin>", line 1, in <module> …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

10
推荐指数
1
解决办法
3354
查看次数

如何从python源代码中删除注释和doc字符串?

有没有我可以这样运行的程序:

py2py.py < orig.py > smaller.py
Run Code Online (Sandbox Code Playgroud)

其中orig.py包含带有注释和doc字符串的python源代码,而small.py包含相同的,可运行的源代码,但没有注释和doc字符串?

最初看起来像这样的代码:

#/usr/bin/python
"""Do something
blah blah...
"""

# Beware the frubnitz!
def foo(it):
    """Foo it!"""
    print it  # hmm?
Run Code Online (Sandbox Code Playgroud)

那么看起来像这样:

def foo(it):
    print it
Run Code Online (Sandbox Code Playgroud)

python comments code-formatting

6
推荐指数
1
解决办法
3631
查看次数

标签 统计

python ×2

code-formatting ×1

comments ×1

python-2.7 ×1