Jak odczytać wiele wierszy surowych danych wejściowych w Pythonie?

Chcę stworzyć program Pythona, który pobiera wiele linii danych wejściowych użytkownika. Na przykład:

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

Jak mogę przyjąć wiele linii surowych danych wejściowych?

Author: Stevoisiak, 2012-07-26

10 answers

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

Aby uzyskać każdą linię jako ciąg znaków, możesz zrobić:

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

Python 3:

'\n'.join(iter(input, sentinel))
 96
Author: jamylak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-13 02:45:12

Alternatywnie możesz spróbować sys.stdin.read(), która zwraca całe wejście do EOF:

import sys
s = sys.stdin.read()
print(s)
 15
Author: Venkat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-18 17:50:40

Czytaj wiersze, dopóki użytkownik nie wprowadzi pustej linii (lub zmieni stopword na coś innego)

text = ""
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text += "%s\n" % line
print text
 7
Author: Junuxx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-26 07:46:24

Po prostu rozszerzam tę odpowiedź https://stackoverflow.com/a/11664652/4476612 zamiast dowolnego słowa stop można po prostu sprawdzić, czy linia jest tam, czy nie

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

Otrzymasz linie na liście, a następnie połącz z \n, aby uzyskać w swoim formacie.

print '\n'.join(content)
 3
Author: Rushikesh Gaidhani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-18 12:59:53

* Sam zmagałem się z tym pytaniem przez tak długi czas, ponieważ chciałem znaleźć sposób, aby odczytać wiele linii danych wejściowych użytkownika bez konieczności kończenia go za pomocą kontrolki D (lub słowa stop). W końcu znalazłem sposób w Python3, używając modułu pyperclip (który będziesz musiał zainstalować za pomocą pip install) Poniżej znajduje się przykład, który bierze listę IPs *

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

Dla mnie to robi dokładnie to, czego szukałem; pobieraj wiele linii danych wejściowych, wykonuj akcje, które są potrzebne (tutaj prosty druk), a następnie przerwać pętlę, gdy ostatnia linia była obsługiwana. Mam nadzieję, że to może być równie pomocne dla ciebie też.

 2
Author: Jon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-24 23:34:37

Spróbuj tego

import sys

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

print(lines)

INPUT:

1

2

3

4

Wyjście: ['1', '2', '3', '4']

 1
Author: Arpitt Desai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-27 10:40:40

Najprostszym sposobem na odczytanie wielu wierszy z monitu / konsoli, gdy znaszdokładną liczbę wierszy , które chcesz przeczytać w Pythonie, jestzrozumienie listy .

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

Powyższy kod czyta 2 linijki. I zapisz dane wejściowe na liście.

 1
Author: KailiC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-19 02:32:49

Sys.stdin.read () może być użyty do pobierania wielowierszowych danych wejściowych od użytkownika. Na przykład

>>> 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
 0
Author: vishnu vardhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-23 16:44:56

Its the best way for writing the code in python > 3.5 version

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

nawet jeśli chcesz ustawić limit dla liczby wartości, możesz przejść jak

while s>0:
a= int(input())
if a:
    list1.append(a)
else:
    break
s=s-1
 0
Author: Дйцрдм Мдтнця,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-11 01:36:57

Bardziej czystym sposobem (bez stop word hack lub CTRL+D) jest użycie Python Prompt Toolkit

Możemy wtedy zrobić:

from prompt_toolkit import prompt

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

Obsługa wejścia jest dość wydajna nawet przy długich wejściach wielowierszowych.

 0
Author: Pratyush,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-05 13:01:08