如何读取多行原始输入?

2024-12-19 09:23:00
admin
原创
91
摘要:问题描述:我想创建一个接受多行用户输入的 Python 程序。例如:This is a multilined input. It has multiple sentences. Each sentence is on a newline. 我怎样才能接收多行原始输入?解决方案 1:sentinel = '' ...

问题描述:

我想创建一个接受多行用户输入的 Python 程序。例如:

This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.

我怎样才能接收多行原始输入?


解决方案 1:

sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
    pass # do things here

要将每一行获取为字符串,您可以执行以下操作:

'
'.join(iter(input, sentinel))

Python 2:

'
'.join(iter(raw_input, sentinel))

解决方案 2:

或者,您可以尝试sys.stdin.read()返回整个输入,直到EOF

import sys
s = sys.stdin.read()
print(s)

解决方案 3:

继续阅读行,直到用户输入空行(或更改stopword为其他内容)

text = ""
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text += "%s
" % line
print text

解决方案 4:

尝试一下

import sys

lines = sys.stdin.read().splitlines()

print(lines)

输入:

1

2

3

4

输出:
[‘1’,‘2’,‘3’,‘4’]

解决方案 5:

只需扩展这个答案https://stackoverflow.com/a/11664652/4476612
而不是任何停用词,您就可以检查某一行是否存在。

content = []
while True:
    line = raw_input()
    if line:
        content.append(line)
    else:
        break

您将获得列表中的行,然后与 \n 连接以获得您的格式。

print '
'.join(content)

解决方案 6:

我自己也为这个问题苦苦思索了很长时间,因为我想找到一种方法来读取多行用户输入,而无需用户使用 Control D(或停用词)来终止它。最后我在 Python3 中找到了一种方法,使用 pyperclip 模块(您必须使用 pip install 进行安装)以下是获取 IP 列表的示例

import pyperclip

lines = 0

while True:
    lines = lines + 1 #counts iterations of the while loop.

    text = pyperclip.paste()
    linecount = text.count('
')+1 #counts lines in clipboard content.

    if lines <= linecount: # aslong as the while loop hasn't iterated as many times as there are lines in the clipboard.
        ipaddress = input()
        print(ipaddress)

    else:
        break

对我来说,这正是我想要的;接受多行输入,执行所需的操作(这里是简单的打印),然后在处理完最后一行时中断循环。希望它也能同样对你有帮助。

解决方案 7:

使用 Python 3,你可以将每一行分配给data

while data := input():
    print("line", data)

解决方案 8:

sys.stdin.read() 可用于从用户那里获取多行输入。例如

>>> import sys
>>> data = sys.stdin.read()
  line one
  line two
  line three
  <<Ctrl+d>>
>>> for line in data.split(sep='
'):
  print(line)

o/p:line one
    line two
    line three

解决方案 9:

当您知道希望 Python 读取的确切行数时,从提示/控制台读取多行的最简单方法是列表理解

lists = [ input() for i in range(2)]

上面的代码读取了 2 行。并将输入保存在列表中。

解决方案 10:

这是用 python >3.5 版本编写代码的最佳方式

a= int(input())
if a:
    list1.append(a)
else:
    break

即使你想限制值的数量,你也可以这样做

while s>0:
a= int(input())
if a:
    list1.append(a)
else:
    break
s=s-1

解决方案 11:

一种更简洁的方法(没有停用词 hack 或 CTRL+D)是使用Python Prompt Toolkit

然后我们可以这样做:

from prompt_toolkit import prompt

if __name__ == '__main__':
    answer = prompt('Paste your huge long input: ')
    print('You said: %s' % answer)

即使是长多行输入,它的输入处理也非常高效。

解决方案 12:

Python Prompt Toolkit 实际上是一个很好的答案,但上面的例子并没有真正展示它。一个更好的例子是来自示例目录的get-multiline-input.py :

#!/usr/bin/env python
from prompt_toolkit import prompt
from prompt_toolkit.formatted_text import HTML


def prompt_continuation(width, line_number, wrap_count):
    """
    The continuation: display line numbers and '->' before soft wraps.
Notice that we can return any kind of formatted text from here.
The prompt continuation doesn't have to be the same width as the prompt
which is displayed before the first line, but in this example we choose to
align them. The `width` input that we receive here represents the width of
the prompt.
    """
    if wrap_count > 0:
        return " " * (width - 3) + "-> "
    else:
        text = ("- %i - " % (line_number + 1)).rjust(width)
        return HTML("<strong>%s</strong>") % text


if __name__ == "__main__":
    print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.")
    answer = prompt(
    "Multiline input: ", multiline=True, prompt_continuation=prompt_continuation
)
    print("You said: %s" % answer)

使用此代码,您可以获得多行输入,其中每行都可以在输入后续行后进行编辑。还有一些不错的附加功能,例如行号。输入通过按 Esc 键然后按 Enter 键结束:

~/Desktop ❯ py prompt.py

按 [Meta+Enter] 或 [Esc] 然后按 [Enter] 接受输入。

多行输入: 第一行文本,然后输入

  • 2 - 第二行文本,然后输入

  • 3 - 第三行文本,箭头键用于移动,输入

  • 4 - 并且可以根据需要编辑行,直到

  • 5 - 按下 Esc 键然后按 Enter 键

你说: 第一行文本,然后输入

第二行文本,然后输入

第三行文本,箭头键用于移动,输入

并且可以根据需要编辑行,直到你

按下 Esc 键然后按 Enter 键

~/Desktop ❯

解决方案 13:

你喜欢这个吗?我模仿了 telnet。这段代码非常直观 :)

#!/usr/bin/env python3

my_msg = input('Message? (End Message with <return>.<return>) 
>> ')

each_line = ''
while not each_line == '.':
    each_line = input('>> ')
    my_msg += f'
{each_line}'

my_msg = my_msg[:-1]  # Remove unwanted period.

print(f'Your Message:
{my_msg}')

解决方案 14:

很简单,做

lst = [x for x in input("Enter numbers seperated by spaces").split("
")]

解决方案 15:

line = input("Please enter lines: ")             
lines = ""             
while line:         
    lines += "
" + line      
    line = input()  
print(lines) 

解决方案 16:

我多年前开发了这个函数,从那时起它就一直发挥着作用,没有任何问题。它远非最优雅、最高效或最快的,当然也没有实现 Python 中的最佳实践。但它是一种简单的算法,可以更容易地翻译成其他语言,因此有一些明显的改进和优化潜力。我甚至不打算在这里发布它,但我认为有人可以从中受益,作为一个起点。

Python 3

def multiline(
        message: str,
        safetyKeyword: list|str,
        show_safetyKeyword: bool = False,
        display_multiline_tag: bool = True,
        show_prompt: bool = True
        ):
    # message : str
    #   Message to be displayed when asking the user for input
    # safetyKeyword : list[str] | str
    #   String (or list of strings) that will break the loop
    # show_safetyKeyword : bool
    #   Determines if the message displayed to the user will contain the list of safety keywords or not
    # display_multiline_tag : bool
    #   Determines whether to display the [ML] tag on every line
    # show_prompt : bool
    #   Flag that controls whether to display the prompt at all.
    #
    # @return str
    # 
    # Usage:
    # >>> text = multiline("Describe how are you felling today.", "--end :)", True)
    # 
    # *** Multiline Interaction - [*nix: Ctrl-D, Windows: Ctrl-Z, to erase previous answer]
    # *** Type one of these words to exit: ['--end :)']
    # *** Describe how are you felling today.
    # [ML] >> Hello
    # [ML] >> This is a test for a multiline input function
    # [ML] >> It has the ability to erase previous linws
    # [ML] >> ^Z
    # [ML] Removed: 'It has the ability to erase previous linws'
    # [ML] >> It has the ability to erase previous lines*. Ops... :)
    # [ML] >> Anyway
    # [ML] >> Cheers
    # [ML] >> --end :)
    #
    # >>> print(text)
    # Hello
    # This is a test for a multiline input function
    # It has the ability to erase previous lines*. Ops... :)
    # Anyway
    # Cheers
    # >>>
    
    # The question needs to be a string to be printed to the user
    if not isinstance(message, str):
        raise TypeError("Message needs to be a string")
    
    # This checks to see if the user provited a list of strings
    # or just a single string. Then a list of strings is created
    # to assure a list of strings (a good candidate for optimization)
    if isinstance(safetyKeyword, list):
        if not all([isinstance(item, str) and len(item) > 0 for item in safetyKeyword]):
            raise TypeError("List of Safety Keywords must contain only non-empty strings")
        safety = [kw.lower() for kw in safetyKeyword]
    elif not isinstance(safetyKeyword, str):
        raise TypeError("Safety Keyword needs to be at least a string")
    else: safety = [safetyKeyword]

    # We are not savages. Have at least one safety keyword
    # otherwise a infinite loop might happen
    if len(safety) < 1:
        raise AssertionError("There must be at least one safety keyword")
    
    # This branch sets up the tag that will be displayed
    # before every line
    if display_multiline_tag: inline_prompt = '[ML] >> '
    else: inline_prompt = ''

    lines = [] # Container for the text
    answer = None # Each line the user inputs

    if show_prompt:
        print("*** Multiline Interaction - [*nix: Ctrl-D, Windows: Ctrl-Z, to erase previous answer]")
        if show_safetyKeyword:
            print("*** Type one of these options to exit:", str(safety)[1:-1])
    print(message)
    # Keep a loop running until the user types a safety keyword
    # In that case, the user wants to finish the text
    # So wraps everything up, and returns the text to the user
    while answer not in safety:
        try:
            # Ask the user's input
            # input() function provides the functionality
            # of throwing exception uppon encountering EOF
            answer = input(inline_prompt)

            # No erase exception thrown so just store the inserted line
            lines.append(answer)
        except EOFError: # User pressed Ctrl-D / Ctrl-Z
            # It'll only try to erase the last line if there is a last line in the first place
            if len(lines) > 0:
                popped = lines.pop()

                # Do something with the removed item, if you want
                # in this case, just print back what was erased
                # and go back asking for input again
                print(inline_prompt, 'Removed:', repr(popped))

    # Returns almost all lines combined with a separation character
    # in this case, a new-line character, could be any character you want :) 
    # The last item in the list will allways be the safety keyword
    return '
'.join(lines[:-1])

解决方案 17:

def sentence_maker(phrase):
    return phrase

results = []
while True:
    user_input = input("What's on your mind: ")
    if user_input == 'end':
        break
    else:
        results.append(sentence_maker(user_input))

print('
'.join(map(str, results)))
相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1000  
  华为作为全球领先的信息与通信技术(ICT)解决方案提供商,其全球化项目的成功离不开高效的项目管理方法。其中,集成产品开发(IPD)流程是华为项目管理体系的核心组成部分。IPD流程不仅帮助华为在复杂的全球化项目中实现了资源的高效整合,还通过跨部门协作和持续优化,确保了项目的高质量交付。本文将通过具体案例,分析华为IPD流...
IPD测试流程   0  
  IPD(Integrated Product Development)是一种以跨职能团队协作为核心的产品开发流程,旨在通过整合资源、优化流程和提高决策效率,实现产品从概念到市场的快速、高效交付。IPD流程的核心思想是将传统的串行开发模式转变为并行开发模式,通过跨部门协作和早期风险识别,减少开发周期中的浪费和返工。这种方...
IPD流程分为几个阶段   0  
  华为的集成产品开发(IPD)流程是企业项目管理中的经典实践,其核心在于通过跨部门协同实现高效的产品开发。IPD流程强调从市场需求到产品交付的全生命周期管理,而跨部门沟通则是这一流程成功的关键。在华为的实践中,跨部门沟通不仅仅是信息的传递,更是团队协作、目标对齐和资源整合的重要手段。本文将深入探讨IPD流程中的跨部门沟通...
IPD项目管理咨询   0  
  IPD流程全称是集成产品开发(Integrated Product Development),它是一种以客户需求为导向、跨部门协作的产品开发模式。与传统产品开发模式相比,IPD强调在产品开发的早期阶段就整合市场、研发、制造、采购等多个部门的资源和能力,通过并行工程和协同工作来提升开发效率。IPD流程的核心在于打破部门壁...
IPD产品开发流程   0  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用