我有這樣的代碼,這是我想打開一個指定的文件,然後每次有一個while循環會算吧,最後輸出特定while循環總數文件。我決定將輸入文件轉換爲一個字典,然後創建一個for循環,每次看到一個單詞後跟一個空格時,會在最後打印WHILE_之前爲WHILE_添加+1計數。在字典(Python)的字數統計
然而,這似乎並沒有工作,我很茫然,爲什麼。任何幫助解決這個問題將不勝感激。
這是我此刻的代碼:
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
爲什麼你給你的變量,離奇和醜陋的名字呢? – abarnert
目前它們只是佔位符 – user2101517
標準庫包括[解析Python代碼的模塊](http://docs.python.org/3.3/library/ast.html)。 –