python计算python文件中的关键字而不计算引号

时间:2015-12-02 18:47:26

标签: python

例如:

import codecs

def main():
    fileName = input("Please input a python file: ")
    file = codecs.open(fileName, encoding = "utf8")
    fornum = 0
    for line in file:
        data = line.split()
        if "for" in data:
            fornum += 1
    print("The number of for loop in", fileName, ":", fornum)

main()

以上代码中有1个for-statement。但该计划的重点是' for'在引号内不是预期的并显示2.我如何更改代码以使其计算关键字(for)而不计算内部的单词""? THX

1 个答案:

答案 0 :(得分:2)

正如在评论中提到的那样,你应该解析Python文件并遍历它AST。您可以使用ast模块执行此操作。示例代码:

import ast

def main():
    fileName = input("Please input a python file: ")
    with open(fileName) as f:
        src = f.read()
        source_tree = ast.parse(src) # get AST of source file
    fornum = 0
    # and recursively walk through all AST nodes
    for n in ast.walk(source_tree):
        if n.__class__.__name__ == "For":
            fornum = fornum+1
    print("The number of for loop in ", fileName, ":", fornum)

main()