Read several lines with Stdin.readlines

1

I have a question with Stdin.readlines, I'm not sure how it's used; for example I have this paragraph

  

Adventures in Disneyland Two blondes were going to Disneyland when   They came to a fork in the road. The sign read: "Disneyland Left." SW   they went home.

But when I print it, it looks like this:

['Adventures in DisneylandTwo blondes were going to Disneyland when they came to  fork in the road. The sign read: "Disneyland Left." So they went home.\n', '\n']

My idea was that each word was separated as an element, but here an element is a phrase, My input is Mensaje=stdin.readlines() , but I do not know how to use this very well, I tried to put a split() or a strip() but this throws me an attribute error.

Can someone explain to me how stdin.readlines() works and what attributes do you have?

Thank you!

    
asked by DDR 28.03.2018 в 22:01
source

1 answer

3

The readlines() method (either over stdin or over another file), which returns you is a list , whose elements are the lines read. Do not separate by phrases, as you said, but by car returns. Every time a car return appears in the entry, that ends a line and that line is added to the list that will eventually be returned.

When you try to apply split() on what returns readlines() logically gives you an error, because what it returns is a list that does not have method split() .

If you want to receive a list of words instead of lines, the simplest solution is to read the complete file with read() , and since in this case you will receive a string, apply the split() method on it, to divide it into words. If you do not pass parameters to split() , you will use spaces or carriage returns indistinctly as word separators.

palabras = sys.stdin.read().split()

Keep in mind, however, one thing. You are reading from the standard input, so the previous line will not return the list of words until the standard input has been "exhausted" (read completely). When you execute the script redirecting the entry from a file, this will happen when you reach the end of the file, which is what we want. But if you run it in interactive mode, the user will have to go typing all the lines, using carriage returns if he wants to separate the lines, and finally pressing Ctrl + D to indicate the end of the entry. As long as Ctrl + D is not pressed, the program will still wait for stdin data.

    
answered by 28.03.2018 / 22:09
source