2013-05-27 61 views
0

我有这样的代码,其中我想张数:代码从文件返回细节,蟒蛇

  • 线进行的.py脚本
  • for_loops(“为”) - while_loops( “同时 ”)
  • if_statements(“ 如果 ”)
  • 函数定义(“ DEF ”)
  • 乘法符号(“ *”
  • 划分标志( “/”
  • 除了标志(“+”)
  • 减法标志(“ - ”)

在数学符号的代码工作,但是当代码正在寻找if语句返回2,当有其中一个是主要问题,但它使我认为我错误地编写了for循环,这可能会在以后出现更多问题。除了这个,我不知道如何打印的出现为[],而不是作者的名作者系

代码:

from collections import Counter 
FOR_=0 
WHILE_=0 
IF_=0 
DEF_=0 
x =input("Enter file or directory: ") 
print ("Enter file or directory: {0}".format(x)) 
print ("Filename {0:>20}".format(x)) 
b= open(x) 
c=b.readlines() 
d=b.readlines(2) 
print ("Author {0:<18}".format(d)) 
print ("lines_of_code {0:>8}".format((len (c)))) 
counter = Counter(str(c)) 
for line in c: 
    if ("for ") in line: 
     FOR_+=1 
     print ("for_loops {0:>12}".format((FOR_))) 
for line in c: 
    if ("while ") in line: 
     WHILE_+=1 
     print ("while_loops {0:>10}".format((WHILE_))) 
for line in c: 
    if ("if ") in line: 
     IF_+=1 
     a=IF_ 
     print ("if_statements {0:>8}".format((a))) 
for line in c: 
    if ("def ") in line: 
     DEF_+=1 
     print ("function_definitions {0}".format((DEF_))) 
print ("multiplications {0:>6}".format((counter['*']))) 
print ("divisions {0:>12}".format((counter['/']))) 
print ("additions {0:>12}".format((counter['+']))) 
print ("subtractions {0:>9}".format((counter['-']))) 

文件被读

'''Dumbo 
Author: Hector McTavish''' 
    for for for # Should count as 1 for statement 
while_im_alive # Shouldn't count as a while 
while blah # But this one should 
    if defined # Should be an if but not a def 
    def if # Should be a def but not an if 
    x = (2 * 3) + 4 * 2 * 7/1 - 2 # Various operators 

任何帮助,将不胜感激

+0

你真的需要使用更多的描述性变量名称。 –

回答

7

不是把源代码以字符串形式,使用ast模块来解析它,然后步行穿过节点:

import ast 
from collections import Counter 

tree = ast.parse(''' 
""" 
Author: Nobody 
""" 

def foo(*args, **kwargs): 
    for i in range(10): 
     if i != 2**2: 
      print(i * 2 * 3 * 2) 

def bar(): 
    pass 
''') 

counts = Counter(node.__class__ for node in ast.walk(tree)) 

print('The docstring says:', repr(ast.get_docstring(tree))) 
print('You have', counts[ast.Mult], 'multiplication signs.') 
print('You have', counts[ast.FunctionDef], 'function definitions.') 
print('You have', counts[ast.If], 'if statements.') 

这是非常简单的,并处理所有的角落情况:

The docstring says: 'Author: Nobody' 
You have 3 multiplication signs. 
You have 2 function definitions. 
You have 1 if statements. 
+0

+1:尽管[它不适用于无效的Python代码,因为在OP的情况下](http://ideone.com/BfkPzb) – jfs

0

if ("if ") in line也算def if #

+0

任何想法如何将其计为1,因为在不计算if后高清? – user2101517

+0

@ user2101517:'if'是一个关键字,所以'def if():'是无效的Python代码。 – Blender

+0

OP的测试代码充满了无效的Python语法。在第一个非评论栏中,它以缩进开头。在一行中有三个'for',没有'var_name in iterable'部分,末尾没有冒号,下一行没有缩进......更多的错误包括大量未定义的变量。 –