Reputation: 720
I have this code, where I am trying to count the number of:
On the mathematical signs the code works, but when the code is looking for if statements it returns 2, when there is one, which is the main problem, but it makes me think I have written the for loop incorrectly, which could bring up more problems later. As well as this I am not sure how to print the Author line which comes up as [] instead of the name of the Author
The code:
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['-'])))
The file being read from:
'''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
Any help would be much appreciated
Upvotes: 0
Views: 112
Reputation: 298196
Instead of treating the source code as a string, use the ast
module to parse it and then just walk through the nodes:
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.')
It's pretty straightforward and handles all of your corner cases:
The docstring says: 'Author: Nobody'
You have 3 multiplication signs.
You have 2 function definitions.
You have 1 if statements.
Upvotes: 7