当我得到多少个单词的次数时,我想将输出保存到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'
最佳答案
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
关于python - 如何将输出保存到txt文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30033531/