程序應該閱讀給定的文件,用字典算每個字的發生,然後創建一個名爲REPORT.TXT和輸出的單詞列表和它們的頻率如何在寫入方法中使用for循環?
infile = open('text file.txt','r')
dictionary = {}
# count words' frequency
for i in range(1,14):
temp = infile.readline().strip().split()
for item in temp:
if dictionary.has_key(item) == False:
dictionary[item] = 1
elif dictionary.has_key:
temp2 = dictionary.get(item)
dictionary[item] = temp2 + 1
infile.close()
outfile = open('report.txt','w')
outfile.write(for words in dictionary:
print '%15s :' %words, dictionary[words])
一切正常的只是在寫輸出的最後一部分右計數部,但 ,我知道我不能在寫方法
爲什麼不把寫的'for'換一換裏面? = D – luk32
http://stackoverflow.com/questions/11198718/writing-to-a-file-in-a-for-loop –