如何将输出保存到txt文件?

时间:2015-05-04 15:08:21

标签: python

当我得到单词的次数时,我想将输出保存到txt文件。但是当我使用以下代码时,输​​出文件中只出现counts。谁知道这里的问题? 非常感谢你!

我的代码:(部分)

d = c.split() # make a string into a list of words
#print d
counts = Counter(d) # count the words 
print(counts)

import sys
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
print 'counts'

3 个答案:

答案 0 :(得分:3)

按照预期工作,python是一种动态语言,它在运行时是一样的。因此,为了捕获所有内容,您必须在脚本的乞讨时重定向stdout。

import sys
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
d = c.split() # make a string into a list of words
#print d
counts = Counter(d) # count the words 
print(counts)

print 'counts'

答案 1 :(得分:0)

import sys
d = c.split() # make a string into a list of words
#print d
counts = Counter(d) # count the words 
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
print(counts)
print 'counts'

print打印到stdout。在打印计数之前,您需要将stdout重新写入文件。

答案 2 :(得分:0)

import sys
from collections import Counter

c = "When I got the number of how many times of the words"
d = c.split() # make a string into a list of words
counts = Counter(d) # count the words 
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
print(str(len(d)) + ' words') #this shows the number of total words 
for i in counts:
    print(str(i), str(counts[i]) + ' counts')

将结果导入 out.txt

12 words
When 1 counts
got 1 counts
many 1 counts
times 1 counts
the 2 counts
words 1 counts
I 1 counts
number 1 counts
how 1 counts
of 2 counts