2013-07-14 112 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 

还有其他各种方法来读取文件要在不同的方式对你的程序,你可以在自己的研究。

相关问题