2014-01-22 31 views
-1

程序應該閱讀給定的文件,用字典算每個字的發生,然後創建一個名爲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]) 

一切正常的只是在寫輸出的最後一部分右計數部,但 ,我知道我不能在寫方法

+0

爲什麼不把寫的'for'換一換裏面? = D – luk32

+0

http://stackoverflow.com/questions/11198718/writing-to-a-file-in-a-for-loop –

回答

5

你需要把writefor循環放一個for循環:

或者您可以使用一個理解,但他們有點忍者,可以是難以閱讀:

outfile.write('\n'.join(['%15s : %s' % key_value for key_value in dictionary.items()])) 
+0

謝謝,真的有幫助! –

+0

當我直接將它打印在外殼上時,它將每個單詞及其頻率打印在一行中,然後在另一行中打印下一個單詞。但是當我把它寫在文件中時,我意識到它們都堵塞在一起。我該如何解決? –

+0

@MandyQuan,我已經編輯了我的答案,在字符串的末尾加上'\ n',這是一個換行符,並確保下一個單詞將在新行上 – mhlester

1

如已在接受的答案已經說了,你需要的for環路write內。但是,使用文件時,最好在with上下文中執行您的操作,因爲這會自動處理文件的關閉。例如

with open('report.txt','w') as outfile: 
    for words in dictionary: 
     outfile.write('%15s : %s\n' % (words, dictionary[words])) 
0

你的代碼中包含幾個不足之處:

  • 不要使用對象的has_key,你不比較/假直接 - 它是多餘的不良作風(用任何語言)

    if dictionary.has_key(item) == False:

應該

`if not item in dictionary` 

值得一提的是,先用積極的測試將是更有效的 - 因爲你可能有一個文件

  • 超過1次的出現絕大多數詞彙dictionary.has_key返回對的引用has_key方法 - 其中布爾等值爲True(您的代碼意外地工作,因爲不管第一個條件第二總是真的)。簡單其他將在條件足夠

  • 最後2所陳述可能只是改寫爲

    dictionary[item] += 1

這就是說,你可以使用集合。計數器計數的話

dictionary = Counter() 
for lines in source_file: 
    dictionary.update(line.split()) 

(順便說一句,之前拆分是多餘的)