簡體   English   中英

如何將輸出保存到txt文件?

[英]How to save the output to txt file?

當我得到多少個單詞的次數時,我想將輸出保存到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'

像python一樣按預期工作是一種動態語言,並且與運行時一樣。 因此,為了捕獲所有內容,您必須在腳本開始時重定向標准輸出。

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'
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重新定向到文件。

另一個稍微好一點的選擇是使用一些較新的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     

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM