programing

파이썬에서 여러 줄의 원시 입력을 어떻게 읽습니까?

goodcopy 2021. 1. 14. 23:13
반응형

파이썬에서 여러 줄의 원시 입력을 어떻게 읽습니까?


여러 줄의 사용자 입력을받는 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(raw_input, sentinel):
    pass # do things here

모든 줄을 문자열로 얻으려면 다음을 수행하십시오.

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

파이썬 3 :

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

사용자가 (또는 변경 빈 줄을 입력 할 때까지 읽는 라인을 계속 stopword뭔가 다른)

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

또는 시도해 볼 수 있습니다. sys.stdin.read()

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

중지 단어 대신 이 답변 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

4

출력 : [ '1', '2', '3', '4']


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

*I struggled with this question myself for such a long time, because I wanted to find a way to read multiple lines of user input without the user having to terminate it with Control D (or a stop word). In the end i found a way in Python3, using the pyperclip module (which you'll have to install using pip install) Following is an example that takes a list of 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

For me this does exactly what I was looking for; take multiple lines of input, do the actions that are needed (here a simple print) and then break the loop when the last line was handled. Hope it can be equally helpful to you too.

ReferenceURL : https://stackoverflow.com/questions/11664443/how-do-i-read-multiple-lines-of-raw-input-in-python

반응형