Python如何输出文件为.txt ?

编程新手……有下面一个Python程序:
from __future__ import division
import nltk
f = open('input.txt', 'r')
file_a = f.read().replace('.', '').replace(',', '')
file_b = file_a.lower()
tokens = nltk.word_tokenize(file_b)
fdist1 = nltk.FreqDist(tokens)
print"Uni-gram"
for key,val in sorted(fdist1.iteritems())[:5]:
print "{1}: {0}".format(key, round(val / len(tokens), 2))
from nltk import bigrams
bi_gram = list(bigrams(tokens))
fdist2 = nltk.FreqDist(bi_gram)
print"Bi-gram"
for key,val in sorted(fdist2.iteritems())[:5]:
print"{1}: {0}".format(key, round(val / len(bi_gram), 2)).replace('(', '').replace("'", "").replace(',', '').replace(')', '')

其中有四个print,请问如何把这四个print的结果输出成一个output.txt文件?
我只会在运行的时候使用 python a.py>./output.txt 命令
但是现在要求把输出指令放在原Python文件中,请问我该怎麼修改我的Python语句?

求大神指导

在程序最前面加上以下三句
import sys
output=open(r'output.txt','w')
sys.stdout=output
在程序最后加上以下两句
sys.stdout=sys.__stdout__
output.close()
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-10-24
创建文件么有几种方法1 常规方法,fp = open("a.txt",*w*)2 使用系统调用,fd = os.open("a.txt",os.O_WRONLY|O_CREAT)
第2个回答  2014-10-24
内容获取失败
第3个回答  2014-10-24
以write方式打开一个文件,如果文件不存在就自动创建
第4个回答  2014-10-24
改后缀
第5个回答  2014-10-23
文件格式并不重要,只要你指定的输出格式对了就行。