while count != 5:
input_text = input("Please insert a number of lines of text \n")
if count != 5:
print("Count is " + str(count))
For the code above, when prompted to supply input, if I paste in a text with multiple line breaks. The code will run for the number of line breaks! I just want it to run ONCE for the entire text.
Can anyone help?
You can use sys.stdin.read() but it will require you to manually send the EOT character:
>>> import sys
>>> x = sys.stdin.read()
the quick brown fox
jumped over the lazy
dog
>>> print(x)
the quick brown fox
jumped over the lazy
dog
>>>
Notice, at the end after I pasted I use Enter and then ctrl-D.
I didn't find the exact answer for you question however i did notice that when you copy in multiple lines of text in the shell it only assigns the first line of text to input_text, then runs again and assigns the second line to input_text, runs agains and third line of input_text. You see.
I think the input statement is not ment for multiple lines though you can sure find some workaround.
This code here shows how each time the loop is ran the variable changes too the next line of that you copied into shell:
count = 0
while True:
count += 1
input_text = input("Please insert a number of lines of text \n")
print("Count is " + str(count))
print("what the variable is set to first time its running the loop: ",input_text,"\n")
Related
I'm working on a project which I want to be able to take words separated by a space, turn it into a string using .split() and then have pyautogui print it out with an "enter" being pressed in between each word. This is the code I have so far below.
# Importing stuff
import pyautogui
# Configure Typing Thing
pyautogui.PAUSE = 0
# Input
input = "hi this is a test run of this program"
# generate words
output_list = input.split()
pyautogui.write(output_list)
pyautogui.press("enter")
Could someone tell me what I did wrong while writing this? Thanks in advance.
Try this:
import pyautogui
pyautogui.PAUSE = 0
input = "hi this is a test run of this program"
output_list = input.split()
for x in output_list:
pyautogui.write(x)
pyautogui.press("enter")
You probably should not use the word input as a variable name as it is a builtin function in Python. To print the words with an enter between them use the following code:
ipt = "hi this is a test run of this program"
ipt = ipt.split()
for word in ipt:
pyautogui.write(word + "\n")
The "\n" is interpreted as a new line character and therefore the write function prints it as a new line (aka an enter)
EDIT: Even easier is something where you replace every space in the string with a newline character and then write that. For example:
ipt = "hi this is a test run of this program"
ipt = ipt.replace(" ", "\n")
pyautogui.write(ipt)
I have a python program which works as a calculator.
import re
value = 0
run = True
while run:
if value == 0:
equation = input('Enter the equation ')
else:
equation=input(str(value))
# print(equation + ' ')
if equation == 'quit':
run = False
else:
equation = re.sub("[a-zA-Z""]",'',equation)
if value ==0:
# equation=eval(equation)
value=eval(equation)
else:
value=eval(str(value)+equation)
print(equation + ' ')
The program works without problem , but when reading the input after the first iteration , the terminal is as below
python3 file.py
Enter the equation 10+10
20+30
The next input can be provided next to 20. I want to add a space before reading the input , so the output will be as shown below
python3 file.py
Enter the equation 10+10
20 +30
How can I add a space before reading the next input so the cursor will create a space
Example
input=input('Enter the input ')
Python Version : 3.7.7
You may simply append a space to the string given to input.
In your example, changing the line equation=input(str(value)) to equation=input(str(value) + ' ') will produce your desired output.
IMHO, this line is not what you want:
equation=input(str(value))
Outputting the result of the calculation should be separate from the next input because of semantics. The argument to input() is the prompt to tell the user what to do. "20" (or whatever intermediate result) is not a good instruction for the user.
So the code becomes
print(value, end=" ") # end=" " prevents a newline and adds a space instead
equation=input() # don't give any prompt, if there's no need to
I have a code that allows a user to choose between 3 options
Ie; Beginner: 1, Intermediate: 2 and Advanced: 3.
However, I'm wanting to generate a paragraph that's assigned to each of the 3 options.
For example
If the user has entered 1 for Beginner, the output will follow with "Hi Beginner! We are going to learn about ....."
The code I've tried thus far is just using the print(" ")option followed by
if f==0:
print("You have entered " + str(inp) + ": " + out).
However, as I'm writing a long paragraph, the output is messy.
Well, i think that you're printing a line without using "\n" in your print text, that's why the output will be always a entire line.
You can use "\n" to write different lines:
print("This is a line\nNow this is other")
Or you can use triple quotes:
print("""This is a line
Now this is other""")
I have a text file with 2000 words, one word on each line. I'm trying to create a code that prints out two random words from the textfile on the same line every 10 seconds. The beginning part of my text file is shown below:
slip
melt
true
therapeutic
scarce
visitor
wild
tickle
.
.
.
The code that I've written is:
from time import sleep
import random
my_file = open("words.txt", "r")
i = 1
while i > 0:
number_1 = random.randint(0, 2000)
number_2 = random.randint(0, 2000)
word_1 = my_file.readline(number_1)
word_2 = my_file.readline(number_2)
print(word_1.rstrip() + " " + word_2.rstrip())
i += 1
sleep(10)
When I execute the code instead of printing two random words it starts printing all the words in order from the top of the text. I'm not sure why this is happening since number_1 and number_2 are inside the loop so every time two words print number_1 and number_2 should be changed to two other random numbers. I don't think replacing number_1 and number_2 outside of the loop will work either since they'll be fixed to two values and the code will just keep on printing the same two words. Does anyone know what I can do to fix the code?
readline() doesn't take any parameters and just returns the next line in your file input*. Instead, try to create a list using readlines(), then choose randomly from that list. So here, you'd make word_list = my_file.readlines(), then choose random elements from word_list.
*Correction: readline() does take a parameter of the number of bytes to read. The documentation for the function doesn't seem to explicitly state this. Thanks E. Ducateme!
my_file.readline(number_1) does not do what you want. The argument for readline is the max size in bytes of a line you can read rather than the position of the line in the file.
As the other answer mentioned, a better approach is to first read the lines into a list and then randomly select words from it:
from time import sleep
import random
my_file = open("words.txt", "r")
words = my_file.readlines()
i = 1
while i > 0:
number_1 = random.randint(0, 2000)
number_2 = random.randint(0, 2000)
word_1 = words[number_1]
word_2 = words[number_2]
print(word_1.rstrip() + " " + word_2.rstrip())
i += 1
sleep(10)
#!/ usr/bin/python3
import sys
def main():
for line in sys.stdin:
line = line.split()
x = -1
for word in line:
if word[-1]==word[0] or word[x-1]==word[1]:
print(word)
main()
It also prints dots at the end of the sentences, why?
And words like 'cat' and 'moon' should also be out of the question. But it also prints these words.
Can someone point me in the right direction please?
I think your problem is because the second and second last characters of 'cat' are the same.
def main():
for line in sys.stdin:
line = line.split()
x = -1
for word in line:
if (word[-1]==word[0] and len(word)<=2) or (word[x-1]==word[1] and len(word)<=4):
print(word)
or something like that, depending on your preference.
This should get rid of that pesky cat, although moon stays.
It will also include words that use upper and lower case characters, so sadly not only will moon print but also Moon, MOon, mooN and moOn.
Edit: Forgot to test for one character words (a, I etc)
import sys
def main():
for line in sys.stdin:
line = line.split()
for word in line:
uword = word.lower()
if len(uword) > 1:
if uword[0:1]==uword[-1] or (uword[1:2]==uword[-2] and len(uword) > 3):
print(word)
main()
I got it guys, understood the question wrong. This prints the right words, that I got beforehand. That cleared things up for me. This is the right code but it still gives "sys.excepthook is missing". I run this code with another code that gives a space an newline. So every space between words becomes a newline:
cat cdb.sentences| python3 newline.py| python3 word.py |head -n 5
import sys
def main():
for line in sys.stdin:
line = line.split()
for word in line:
letterword = lw = word.lower()
if len(lw) > 1:
if lw[0:1]==lw[-1] and (lw[1:2]==lw[-2]):
print(word)
main()
import sys
def main():
for line in sys.stdin:
line = line.rstrip()
text = ""
for word in line:
if word in ' ':
text=text + '\n'
else:
text=text + word
print(text)
main()
It should give the 5 first words that have the same first, last letter, -2 and 1 letters. With an white line between each one of them. First i want to solve that hook.
Thx
You are not helping yourself by answering your own question with what is essentially a completely different question in an answer.
You should have closed your original off by accepting one of the answers, if one of them helped, which it looked like they did and then asked a new question.
However, the answer to your 2nd question/answer can be found here:
http://python.developermemo.com/7757_12807216/ and it is a brilliant answer
Synopsis:
The reason this is happening is that you're piping a nonzero amount of output from your Python script to something which never reads from standard input. You can get the same result by piping to any command which doesn't read standard input, such as
python testscript.py | cd .
Or for a simpler example, consider a script printer.py containing nothing more than
print 'abcde'
Then
python printer.py | python printer.py
will produce the same error.
The following however will trap the sys.excepthook error:
import sys
import logging
def log_uncaught_exceptions(exception_type, exception, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(exception_type, exception))
sys.excepthook = log_uncaught_exceptions
print "abcdfe"