78

複数行のユーザー入力を受け取るPythonプログラムを作成したいと思います。例えば:

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

生の入力の複数の行をどのように取り込むことができますか?

4

14 に答える 14

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

すべての行を文字列として取得するには、次のようにします。

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

Python 2:

'\n'.join(iter(raw_input, sentinel))
于 2012-07-26T07:47:56.870 に答える
18

sys.stdin.read()または、次のようになるまで入力全体を返すようにすることもできEOFます。

import sys
s = sys.stdin.read()
print(s)
于 2017-05-01T10:21:41.573 に答える
7

ユーザーが空の行を入力するまで(または別の行に変更stopwordするまで)行を読み続けます

text = ""
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text += "%s\n" % line
print text
于 2012-07-26T07:46:24.547 に答える
3

ストップワードの代わりにこの回答を拡張するだけでhttps://stackoverflow.com/a/11664652/4476612 行があるかどうかを確認できます

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

リスト内の行を取得してから、\nと結合してフォーマットを取得します。

print '\n'.join(content)
于 2018-01-18T12:59:53.710 に答える
2

これを試して

import sys

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

print(lines)

入力:

1

2

3

4

出力: ['1'、 '2'、 '3'、 '4']

于 2018-09-27T09:31:22.680 に答える
2

*ユーザーがコントロール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('\n')+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

私にとって、これはまさに私が探していたものです。複数行の入力を取り、必要なアクション(ここでは単純な印刷)を実行してから、最後の行が処理されたときにループを中断します。それがあなたにも同様に役立つことを願っています。

于 2019-01-24T23:34:37.287 に答える
1

Pythonに読み取らせたい正確な行数がわかっている場合に、プロンプト/コンソールから複数の行を読み取る最も簡単な方法は、リスト内包表記です。

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

上記のコードは2行を読み取ります。そして、入力をリストに保存します。

于 2020-03-09T04:16:51.900 に答える
0

sys.stdin.read()を使用して、ユーザーから複数行の入力を受け取ることができます。例えば

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

o/p:line one
    line two
    line three
于 2019-01-23T16:44:56.787 に答える
0

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
于 2020-08-10T16:37:52.793 に答える
0

よりクリーンな方法(ストップワードハックやCTRL + Dなし)は、PythonPromptToolkitを使用することです。

その後、次のことができます。

from prompt_toolkit import prompt

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

入力処理は、長い複数行の入力でもかなり効率的です。

于 2021-01-05T13:01:08.250 に答える
0

Python Prompt Toolkitは実際には優れた答えですが、上記の例では実際には示されていません。より良い例は、examplesディレクトリの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❯pyprompt.py
[Meta + Enter]または[Esc]を押してから[Enter]を押して、入力を受け入れます。
複数行入力:テキストの最初の行、次に入力-2-2行
目のテキスト、次に入力-3-3 行
目のテキスト、矢印キーで移動し、
-4と入力します。行は必要に応じて編集できます。
5-エスケープキーを押してからEnterキーを押し
ますあなたが言った:最初のテキスト行、次に
2行目のテキストを入力し、次に
3行目のテキストを入力すると、矢印キーが動き回り、Enterキーを押して、
必要に応じて行を編集できます。 Escキーを
押してからEnterキーを押します
〜/デスクトップ❯</ p>

于 2021-08-07T08:29:21.393 に答える
0

これはどうですか?telnetを模倣しました。スニペットは非常に自明です:)

#!/usr/bin/env python3

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

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

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

print(f'Your Message:\n{my_msg}')
于 2021-11-29T03:47:22.977 に答える
0

Python 3では、各行をdata次のように割り当てることができます。

while data := input():
    print("line", data)
于 2022-02-04T12:02:01.737 に答える
-1
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('\n'.join(map(str, results)))
于 2022-02-27T09:33:24.473 に答える