【问题标题】:returning specifics from a file, python从文件返回细节,python
【发布时间】:2013-05-27 00:22:35
【问题描述】:

我有这段代码,我想在其中计算:

  • .py 脚本中的代码行数
  • for_loops ("for") -while_loops ("while")
  • 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

任何帮助将不胜感激

【问题讨论】:

  • 你真的需要使用更具描述性的变量名。

标签: python return


【解决方案1】:

不要将源代码视为字符串,而是使用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.
【解决方案2】:

if ("if ") in line 也将计入 def if #

【讨论】:

  • 知道如何仅将其计为 1,例如不计算 def 之后的 if 吗?
  • @user2101517: if 是关键字,所以def if(): 是无效的 Python 代码。
  • OP 的测试代码中充满了无效的 Python 语法。就在第一个非注释行,它以缩进开头。连续三个fors,没有var_name in iterable 部分,末尾没有冒号,下一行没有缩进……更多错误,包括下一行中有大量未定义的变量。
猜你喜欢
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 2014-06-28
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多