raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
Python 3
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
Python 2
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
Answer from xiaket on Stack Overflowraw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
Python 3
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
Python 2
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n
To get multi-line input from the user you can go like:
no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
lines+=input()+"\n"
print(lines)
Or
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
multiline input in terminal - Ideas - Discussions on Python.org
Store multi-line input into a String (Python) - Stack Overflow
Reading multiple lines of input
What have you tried, and what form does the input take? If it's typed in, maybe you want something like this:
lines = []
line = input('First line: ')
while line:
lines.append(line)
line = input('Next line: ')
print(lines)If you get the input from some source all at once, you can use
the_input.split('\n') More on reddit.com How do I process a multiple line input from "for line in sys.stdin:"?
Videos
I'm trying to feed a prompt to a GPT-2 model, which is trained on song lyrics. With this model, you can feed it a prompt and it will attempt to finish it. The problem I'm having is that I need for the prompt to be formatted correctly like song lyrics - with each lyric on a newline. Since this model has been trained on formatted lyrics, the prompt needs to look the same to produce above average results.
input() doesn't work, because hitting return submits the text. I've also tried sys.stdin.read() as well and nothing seems to happen, just returns ' '.
Is it because I'm running it in a notebook? I'm only like 8 months deep into this python hobby, so I could be asking for something that can't happen.
Here's the code, would appreciate any ideas you've got.
prompt = input('Input Prompt:')
gpt2.generate(sess,
length=200,
temperature=.99,
prefix= prompt, #this is where the prompt goes
nsamples=5,
top_p=.9,
batch_size=5,
run_name='run1'
)
To take multiple lines of input and put them in a list of strings, you can use sys.stdin.readlines() which will keep accepting returns until you give it an EOF [ctrl + d in *nix, ctrl + z in Windows].
E.g.:
user_input = sys.stdin.readlines("Favourite foods followed by EOF:") # User gives input...
print(user_input)
Output:
>> ["Spam\n", "Spam\n", "Spam\n"]
Obviously this leaves you with newlines, so you could do something hacky like:
user_input = [line.rstrip() for line in sys.stdin.readlines()]
Which will give you:
>> ["Spam", "Spam", "Spam"]
Sounds like an interesting ML problem, though dealing with a list of strings may complicate things significantly. You might want to make them one long string using something like join, e.g.
" ".join(user_input) # Used with a separator of " ", but you could use newlines or something
Which gives one string of:
>> "Spam Spam Spam"
Can't you use a while loop to read the input? e.g.
prompt = []
line = input("Input prompt ending with an empty line: ")
while line:
prompt.append(line)
line = input()
prompt = "\n".join(prompt)
You can use readlines() method of file objects:
import sys
userInput = sys.stdin.readlines()
You can easily create one, using generators. Here is one such implementation. Note you can either press a blank return or any Keyboard Interrupt to break out of the inputloop
>>> def multi_input():
try:
while True:
data=raw_input()
if not data: break
yield data
except KeyboardInterrupt:
return
>>> userInput = list(multi_input())
359716482
867345912
413928675
398574126
>>> userInput
['359716482', '867345912', '413928675', '398574126']
>>>
So I'm trying to get into regular programming practice. Spent some time doing challenges at CodeEval and the likes with C++ a little ways back, but now that I'm coming back I want to focus a little on Python.
The problem is, I can't figure out how to read the multiple line input test cases for my first program. In C++ it was easy with a while/get loop, but I'm struggling to figure it out in Python. It's frustrating because I know its simple and I've done it before, but I can't for the life of me figure out this simple problem that is holding me back from solving the bigger tasks.
So the test case for example would be:
SetCol 32 10
SetRow 20 4
QueryRow 10
etc, and I need to run my functions on each line of input.
Any advice as the best way to do this would be appreciated, so I can get back to practicing!
What have you tried, and what form does the input take? If it's typed in, maybe you want something like this:
lines = []
line = input('First line: ')
while line:
lines.append(line)
line = input('Next line: ')
print(lines)
If you get the input from some source all at once, you can use
the_input.split('\n')
def parse():
n1, x1, y1 = raw_input().split(" ")
n2, x2, y2 = raw_input().split(" ")
n3, x3, y3 = raw_input().split(" ")
return [(n1,x1,y1), (n2,...)..]
inputs = [parse() for _ in range(len(tests)/3)]
in case you don't know how many tests are you need to read the whole input first:
import sys
lines = sys.stdin.readlines()
def parse(i):
n1, x1, y1 = lines[i].split(" ")
n2, x2, y2 = lines[i+1].split(" ")
n3, x3, y3 = lines[i+2].split(" ")
return [(n1,x1,y1), (n2,...)..]
inputs = [parse(i) for i in range(len(lines)/3)]
I recently took a coding assessment where I was tasked to compute the square of the input which is relatively easy. The issue was that the input was a multiple line input:
7
16
and the expected output is
49
256
The given code was
for line in sys.stdin:
# your code here
print(line, end="")I tried to do ls = list(line.split()) but ls[0] is
['7']
['16']
and ls[1] is None
I also tried ls = list(line.split('\n')) but ls is
['7', '']
['16', '']
So how was I supposed to process the input to get ['7', '16'] rather than a 2 dimensional list?
From there I know how continue with make it an integer using map, creating a for loop for each item of the list and printing the square of each item.
I dont have a picture of the question since I was monitored on webcam but this is roughly what I remembered from the question.
edit: It was an online assessment platform so I am not sure exactly how the input was written as (like the raw input). Also I can only modify the code inside for line in sys.stdin:
Also, does anyone know how to write the input for sys.stdin using jupyternotebook such that I can practice this problem?