0

我希望将控制台输出写入文件,如何将控制台输出重定向到文件“c1.txt”?请帮忙。这是我的代码:

from collections import Counter
from glob import iglob
import re
import os

def removegarbage(text):
    # Replace one or more non-word (non-alphanumeric) chars with a space
    text = re.sub(r'\W+', ' ', text)
    text = text.lower()
    return text

topwords = 100
folderpath = 'path/to/directory'
counter = Counter()
for filepath in iglob(os.path.join(folderpath, '*.txt')):
    with open(filepath, 'r') as filehandle:
        counter.update( removegarbage(filehandle.read()).split() )

for word, count in counter.most_common(topwords):
    print ('{}: {}'.format(count, word))
4

0 回答 0