2016-11-29 32 views
0

这是我的代码1.4.3上的文件

sentext = open("urSentence.txt", "w") 
UserSen = input("Enter your sentence of your choice, ") 
print (UserSen) 
sentext.close() 
postext = open("ThePos.txt", "w") 
listSplit = UserSen.split() 
X = {} #this will make the words in a sentence assigned to a number 
position=[] 
for i,j in enumerate(listSplit): #"i" will count how many words there are in the sentence 
    if j in X: 
     position.append(X[j]) 
    else: 
     X[j]=i 
     position.append(i) 
print (position) 
postext.close() 

它使文件,但它不保存其中的任何东西。我究竟做错了什么?

+4

不保存* *什么上呢?你从不写任何东西或从文件中读取任何东西。 – jonrsharpe

+0

你只是打开和关闭文件 – 0xtvarun

+0

f.write('This is a test \ n')用这个来保存文件里面的文字 – Hikaryu

回答

6

你从来没有写过以任何方式任何文件。你可以用几种方法来做到这一点。既然你已经在使用什么样子的Python 3的print功能,尝试file参数:

print(UserSen, file=sentext) 

... 

print(position, file=postext) 
+3

从来不知道打印有写入文件的选项。很高兴知道! +1 –

+0

这工作,谢谢 – Romeme

1

print函数不会写入文件。你需要明确地写信给它。

sentext = open("urSentence.txt", "w") 
UserSen = input("Enter your sentence of your choice, ") 
sentext.write(UserSen) 
sentext.close() 

和类似:

postext = open("ThePos.txt", "w") 
... 
postext.write(str(position)) 
postext.close() 
+0

'position'是一个列表。你不能直接将它写入文件。 – TigerhawkT3

+0

没有注意到 - 编辑 – Billy