2016-11-29 29 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