2014-01-22 29 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()) 

(顺便说一句,之前拆分是多余的)