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)
Related
I'm trying to making a program where each keypress prints the next character in a predetermined string, so it's like the user is typing text.
Here's the code I'm trying to use:
def typing(x):
letter = 0
for i in range(0, len(x)):
getch.getch()
print(x[letter], end = "")
letter += 1
typing("String")
What happens here is you need to press 6 keys (The length of the string) and then it prints all at once. I can sort of fix this by removing the , end = "", which makes the letters appear one at a time, but then the outcome looks like this:
S
t
r
i
n
g
Any ideas for making the letters appear one at a time and stay on the same line?
You can try this code which works for me:
import time
def typewrite(word: str):
for i in word:
time.sleep(0.1)
print(i, end="", flush = True)
typewrite("Hello World")
I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]
I am looking to create just a small module to implement the ability to text scroll. I've tried a few things so far and this is what I'm sitting on:
from time import sleep
def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
print x
text_scroll("hello world.")
With all this I am hoping to have it print "hello", sleep for a second, "world". The best I've gotten so far is it returning None instead of actually pausing.
Try the following code:
from time import sleep
from sys import stdout
def text_scroll(text):
words = text.split()
for w in words:
print w,
stdout.flush()
sleep(1)
The comma at the end of the print does not add new line '\n'.
The flush() function flushes the word into the screen (standard output).
If it is python 2.7, you can do the following, which is what volcano suggested.
from time import sleep
def text_scroll(x):
for word in x.split():
print word,
sleep(1)
text_scroll("Hello world")
This works because it splits the input into individual words and then prints them, sleeping between each word. The print word, is python 2.7 for print word, without a newline ,.
Yours doesn't work for several reasons:
def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
this function doesn't do anything with the variable that it makes, and it mangles it:
def text_scroll(x):
x = x.split() # x = ["Hello", "world"]
#here is where I'd like to add the sleep function
x = " ".join(x) # x = "Hello world"
It doesn't actually do anything with the result, so it gets thrown away. But it's also important to realize that because it is a def, it doesn't execute until it is called.
when you print x, x hasn't been set, so it should give you a NameError: name 'x' is not defined
Finally, you call your function text_scroll("hello world.") which doesn't output anything, and it finishes.
for word in x.split():
print word,
time.sleep(1)
Comma prevents print from adding line feed to your output
#!/ 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"
My sample text file is: 'abcd abcd abcd'
The program has a dictionary with symbols dedicated for each letter. The objective is to create a new file with the files message encrypted.
Program 'works'. By this I mean that it only converts abc. Since theres no d in the dictionary then it raises an error. I removed the d and tried again, but this raises another error called: KeyError: ' '
How can I make my program detect spaces, and write the letter even if theres no symbol for it?
def main():
ecrypt = {'a':'%', 'b':'&', 'c':'/'}
input_file = open('efile.txt', 'r')
output_file = open('newefile.txt', 'w')
line = input_file.readline()
for letter in line:
if letter in line:
output_file.write(ecrypt[letter])
main()
You can use a try-except for handle the KeyError but as a more pythonic way you can use str.translate() function that is actually for this aim :
>>> from string import maketrans
>>> i='abc'
>>> o='%&/'
>>> trantab = maketrans(i, o)
>>> print 'abcd abcd abcd'.translate(trantab)
%&/d %&/d %&/d
and for translate the file and write in another file :
from string import maketrans
i='abc'
o='%&/'
trantab = maketrans(i, o)
with open('efile.txt', 'r') as infile,open('newefile.txt', 'w') as out :
out.write(infile.read().translate(trantab))
You're trying to access ecrypt['d'] which doesn't exist. With this current code, you'd need to make sure every character (not just letter, punctuation... Spaces...) is in the ecrypt dict.
I suggest adding an exception. See https://docs.python.org/2/tutorial/errors.html
The 'if letter in line' is superfluous.
for letter in line:
try:
output_file.write(ecrypt[letter])
except KeyError:
output_file.write(letter)
Or, test that the letter exists first.
for letter in line:
cipher_letter=ecrypt[letter] if letter in ecrypt else letter
output_file.write(cipher_letter)