複数行のユーザー入力を受け取るPythonプログラムを作成したいと思います。例えば:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
生の入力の複数の行をどのように取り込むことができますか?
複数行のユーザー入力を受け取るPythonプログラムを作成したいと思います。例えば:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
生の入力の複数の行をどのように取り込むことができますか?
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))
sys.stdin.read()
または、次のようになるまで入力全体を返すようにすることもできEOF
ます。
import sys
s = sys.stdin.read()
print(s)
ユーザーが空の行を入力するまで(または別の行に変更stopword
するまで)行を読み続けます
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
print text
ストップワードの代わりにこの回答を拡張するだけでhttps://stackoverflow.com/a/11664652/4476612 行があるかどうかを確認できます
content = []
while True:
line = raw_input()
if line:
content.append(line)
else:
break
リスト内の行を取得してから、\nと結合してフォーマットを取得します。
print '\n'.join(content)
これを試して
import sys
lines = sys.stdin.read().splitlines()
print(lines)
入力:
1
2
3
4
出力: ['1'、 '2'、 '3'、 '4']
*ユーザーがコントロール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
私にとって、これはまさに私が探していたものです。複数行の入力を取り、必要なアクション(ここでは単純な印刷)を実行してから、最後の行が処理されたときにループを中断します。それがあなたにも同様に役立つことを願っています。
Pythonに読み取らせたい正確な行数がわかっている場合に、プロンプト/コンソールから複数の行を読み取る最も簡単な方法は、リスト内包表記です。
lists = [ input() for i in range(2)]
上記のコードは2行を読み取ります。そして、入力をリストに保存します。
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
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
よりクリーンな方法(ストップワードハックやCTRL + Dなし)は、PythonPromptToolkitを使用することです。
その後、次のことができます。
from prompt_toolkit import prompt
if __name__ == '__main__':
answer = prompt('Paste your huge long input: ')
print('You said: %s' % answer)
入力処理は、長い複数行の入力でもかなり効率的です。
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>
これはどうですか?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}')
Python 3では、各行をdata
次のように割り当てることができます。
while data := input():
print("line", data)
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)))