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

Python 如何将输出保存到txt文件?,python,Python,当我得到单词的次数时,我想将输出保存到一个txt文件中。但是当我使用下面的代码时,输出文件中只显示了计数。有人知道这里的问题吗? 多谢各位 我的代码:(部分) 打印打印到标准输出。在打印计数数之前,您需要将stdout重新更正到文件中。像python那样工作是一种动态语言,一切都与运行时一样。因此,为了捕获所有内容,您必须在脚本请求时重定向stdout import sys sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "

当我得到单词的次数时,我想将输出保存到一个
txt
文件中。但是当我使用下面的代码时,输出文件中只显示了
计数
。有人知道这里的问题吗? 多谢各位

我的代码:(部分)


打印
打印到标准输出。在打印计数数之前,您需要将stdout重新更正到文件中。

像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'

另一个稍微好一点的选择是使用一些较新的Python特性:

from __future__ import print_function

with open(r'c:\Users\Administrator\Desktop\out.txt', 'w') as f:
    d = c.split() # make a string into a list of words
    #print(d, file=f)
    counts = Counter(d) # count the words 
    print(counts, file=f)

    print('counts', file=f)
或者,您可以使用日志记录模块:

import logging

logger = logging.getLogger('mylogger')
logger.addHandler(logging.FileHandler(filename=r'c:\Users\Administrator\Desktop\out.txt'))
logger.setLevel(logging.DEBUG)


wordlist = c.split()
logger.debug('Wordlist: %s', wordlist)

logger.debug('Counting words..')
counts = Counter(wordlist)
logger.debug('Counts: %s', counts)
在Windows上,您可以使用非常有用的应用程序在程序执行时查看日志

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')
将te结果输入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     

难道你不想打印“计数”吗?现有答案中是否缺少一些不能解决你问题的东西?如果没有,你能选择一个适合你的作为被选中的一个,这样未来的人们将能够很快找到他们需要的答案吗?当然。他们都很适合我。我来选一个。对不起:)非常感谢。顺便说一句,我可以问一下如何计算输出中有多少(不同的)单词吗?例如,在本例中,我有10个单词(当我得到单词的多少倍时)。我添加了一行代码,其中写入
out.txt
总单词数。
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')
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