有谁知道如何将此代码的输出保存到文件?

时间:2016-11-16 12:12:17

标签: python

sentence = input('Please enter your sentence: ')
words = sentence.split()

positions = {word:index for index, word in reversed(list(enumerate(words, 1)))}

print(' '.join(str(positions.get(word)) for word in words))

2 个答案:

答案 0 :(得分:0)

这个问题不够通用,我认为它应该是“如何在python中编写文件”,另外,你可能想在这里询问之前阅读文档。

https://docs.python.org/2/tutorial/inputoutput.html

with open('filename', 'w') as the_file:
    the_file.write(whatever)

答案 1 :(得分:0)

f = open('out.txt', 'w')
f.write('...\n')
f.close()

此信息来自How to redirect 'print' output to a file using python?  ;)

f.open=('PathToFile', 'w')
sentence = input('Please enter your sentence: ')
    words = sentence.split()
    positions = {word:index for index, word in reversed(list(enumerate(words, 1)))}
    f.write(' '.join(str(positions.get(word)) for word in words))
f.close