我有这段代码,我想打开一个指定的文件,然后每次有一个while循环它都会计算它,最后输出特定文件中的while循环总数。我决定将输入文件转换为字典,然后创建一个 for 循环,每次看到单词 while 后跟一个空格时,它都会在最后打印 WHILE_ 之前为 WHILE_ 添加 +1 计数。
但是,这似乎不起作用,我不知道为什么。任何解决此问题的帮助将不胜感激。
这是我目前的代码:
WHILE_ = 0
INPUT_ = input("Enter file or directory: ")
OPEN_ = open(INPUT_)
READLINES_ = OPEN_.readlines()
STRING_ = (str(READLINES_))
STRIP_ = STRING_.strip()
input_str1 = STRIP_.lower()
dic = dict()
for w in input_str1.split():
if w in dic.keys():
dic[w] = dic[w]+1
else:
dic[w] = 1
DICT_ = (dic)
for LINE_ in DICT_:
if ("while\\n',") in LINE_:
WHILE_ += 1
elif ('while\\n",') in LINE_:
WHILE_ += 1
elif ('while ') in LINE_:
WHILE_ += 1
print ("while_loops {0:>12}".format((WHILE_)))
这是我正在使用的输入文件:
'''A trivial test of metrics
Author: Angus McGurkinshaw
Date: May 7 2013
'''
def silly_function(blah):
'''A silly docstring for a silly function'''
def nested():
pass
print('Hello world', blah + 36 * 14)
tot = 0 # This isn't a for statement
for i in range(10):
tot = tot + i
if_im_done = false # Nor is this an if
print(tot)
blah = 3
while blah > 0:
silly_function(blah)
blah -= 1
while True:
if blah < 1000:
break
输出应该是 2,但我的代码现在打印 0