如何读取多行原始输入?
- 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 = '' # 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)))
- 2024年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)
- 项目管理必备:盘点2024年13款好用的项目管理软件