【问题标题】:Python: How to store user text input in a file?Python:如何将用户文本输入存储在文件中?
【发布时间】:2013-07-12 17:15:23
【问题描述】:

我正在尝试提示用户输入一段文本,直到他/她在单独的行上键入 EOF。之后,程序应该为他/她提供一个菜单。当我转到选项 1 时,它只打印出 EOF,而不是之前输入的所有内容。这是为什么呢?

假设我输入“嗨,我喜欢馅饼”作为我的文本块。我键入 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)

【问题讨论】:

    标签: python file text input store


    【解决方案1】:

    原因是在你的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
    

    【讨论】:

    • 感谢您的快速响应先生。
    • 没问题!希望对您有所帮助!
    【解决方案2】:

    当你设置时

    textInput = input()
    

    你扔掉旧的输入。如果你想保留所有的输入,你应该做一个列表:

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

    【讨论】:

      【解决方案3】:

      每次用户输入新行时,您的 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
      

      【讨论】:

        【解决方案4】:

        您需要在输入时保存在 while 循环中输入的每一行。每次用户键入新行时,变量 textInput 都会被覆盖。您可以像这样将文本存储到文本文件中:

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

        在 while 循环中的 if 之后将其作为 elif 语句插入。 “\n”是一个换行命令,在阅读文本时不会显示,而是告诉计算机开始一个新行。

        要读取此文件,请使用以下代码:

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

        还有多种其他方法可以根据您的程序以不同的方式读取文件,您可以自行研究。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-23
          • 1970-01-01
          • 1970-01-01
          • 2016-02-12
          • 2022-10-15
          • 2019-09-13
          • 1970-01-01
          相关资源
          最近更新 更多