0

我有一个 for 循环,它遍历一个文本文件(在这种情况下实际上是一个 Python 文件),它试图提取所有函数(寻找单词def)。一旦它找到那个词,它就会开始记录行,直到它碰到一个空格(我用它来表示函数的结尾)。

def我的问题是,一旦我在文件中点击 a 并记录可能出现在函数之前的任何注释,我就想备份。例如:# This function does the following...等。我想备份,直到我不再遇到哈希。

我将如何用我写的这个循环向后看?

for (counter,line) in enumerate(visible_texts):
    line= line.encode('utf-8')
# if line doesn't contain def then ignore it
    if "def" in line and infunction== 0:
        match = re.search(r'\def (\w+)', line.strip())
        line = line.split ("def")[1]    
        print "Recording start of the function..."
        # Backup to see if there's any hashes above it (until the end of the hashes) ** how do I do this **

我最后想要的输出示例是:

# This function was created by Thomas
# This function print a pass string into the function    
def printme( str ):
       "This prints a passed string into this function"
       print str
       return
4

2 回答 2

5

不要备份;无论如何都要记录评论,直到你打到另一行。如果它不是def一行,则丢弃收集的评论:

comments = []
for (counter, line) in enumerate(visible_texts):
    if line.lstrip().startswith('#'):
        comments.append(line)
    elif "def" in line and not infunction:
        comment = '\n'.join(comments)
        comments = []
        # rest of your code
    else:
        comments = []
于 2012-12-22T19:09:23.300 回答
0

您可以使用该ast模块来解析python 代码。

您应该养成使用文档字符串而不是注释来描述函数的习惯。

优点之一是该ast模块可以使用ast.get_docstring().

于 2012-12-22T19:44:00.440 回答