2013-07-14 114 views
0

我試圖提示用戶輸入一段文字,直到他/她自己在單獨一行中鍵入EOF。之後,程序應該向他/她提供一個菜單。當我進入選項1時,它僅打印出EOF,而不是之前輸入的所有內容。爲什麼是這樣?Python:如何將用戶文本輸入存儲在文件中?

假設我輸入「Hi I like pie」作爲我的文本塊。我輸入EOF進入菜單並輸入選項1.我希望「嗨,我喜歡餡餅」彈出,但只有字母EOF。我該如何解決?如何「提供」Python文件?

#Prompt the user to enter a block of text. 
done = False 
while(done == False): 
    textInput = input() 
    if textInput == "EOF": 
     break 

#Prompt the user to select an option from the Text Analyzer Menu. 
print("Welcome to the Text Analyzer Menu! Select an option by typing a number" 
    "\n1. shortest word" 
    "\n2. longest word" 
    "\n3. most common word" 
    "\n4. left-column secret message!" 
    "\n5. fifth-words secret message!" 
    "\n6. word count" 
    "\n7. quit") 

option = 0 

while option !=7: 
    option = int(input()) 

    if option == 1: 
     print(textInput) 

回答

0

的原因是,在你的while循環,你循環,直到textInput等於EOF,所以你只能打印EOF

你可以嘗試這樣的事情(使用nextInput變量「預覽」下一個輸入):

#Prompt the user to enter a block of text. 
done = False 
nextInput = "" 
while(done == False): 
    nextInput= input() 
    if nextInput== "EOF": 
     break 
    else: 
     textInput += nextInput 
+0

謝謝您的快速響應先生。 – user2581724

+0

沒問題!希望能幫助到你! – jh314

0

當您設置

textInput = input() 

你扔掉舊的輸入。如果你想保留所有的輸入,你應該做一個列表:

input_list = [] 
text_input = None 
while text_input != "EOF": 
    text_input = input() 
    input_list.append(text_input) 
0

每次用戶鍵入一個新行,你爲textInput變量被覆蓋。

你可以做

textInput = '' 
done = False 
while(done == False): 
    input = input() 
    if input == "EOF": 
     break 
    textInput += input 

而且,你不需要同時使用done變量和break語句。 你既可以做

done = False 
while(done == False): 
    textInput += input() 
    if textInput == "EOF": 
     done = True 

while True: 
    textInput += input() 
    if textInput == "EOF": 
     break 
0

您需要保存在你的while循環類型的每一行,因爲它是類型化。每次用戶輸入新行時,變量textInput都將被覆蓋。您可以使用存儲文本到這樣一個文本文件:

writer = open("textfile.txt" , "w") 
writer.write(textInput + "\n") 

後插入此爲elif的語句如果您在while循環。 「\ n」是一個新的行命令,它在讀取文本時不會顯示,但會通知計算機開始一個新行。

爲了讀取這個文件,使用此代碼:

reader = open("textfile.txt" , "r") 
print(reader.readline()) #line 1 
print(reader.readline()) #line 2 

還有其他各種方法來讀取文件要在不同的方式對你的程序,你可以在自己的研究。

相關問題