为了账号安全,请及时绑定邮箱和手机立即绑定

从文件返回详细信息,python

从文件返回详细信息,python

慕码人8056858 2021-03-07 17:20:40
我有这段代码,在这里我要计算的数量:.py脚本中的代码行for_loops(“ for”)-while_loops(“ while”)if_statements(“ if”)函数定义(“ def”)乘法符号(“ *”划分标志(“ /”加号(“ +”)减号(“-”)在数学符号上,代码有效,但是当代码正在寻找if语句返回2时,则存在一个,这是主要问题,但是这让我觉得我写错了for循环,这可能会带来更多错误以后出现问题。除此之外,我不确定如何打印显示为[]而不是Author name的Author行代码:from collections import CounterFOR_=0WHILE_=0IF_=0DEF_=0x =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['-'])))正在从以下文件读取文件:'''DumboAuthor: Hector McTavish'''    for for for  # Should count as 1 for statementwhile_im_alive # Shouldn't count as a whilewhile 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任何帮助将非常感激
查看完整描述

2 回答

?
长风秋雁

TA贡献1757条经验 获得超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.


查看完整回答
反对 回复 2021-03-27
?
GCT1015

TA贡献1827条经验 获得超4个赞

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


查看完整回答
反对 回复 2021-03-27
  • 2 回答
  • 0 关注
  • 292 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信