I don't know how to use regular expression in a pile of code and I'm not sure how to code it correctly either. I tried to lookup for tutorial, guides, everything. But I'm still not understand about it, so please help me to fix my stupid code.
Summary of the working, I'm trying to code a small program that controls my computer keyboard through pyserial and with the help of microbit. For example, when button A is pressed, the microbit sends data to my computer through uart and my python shell at the end receiving the message, try to match it and execute the respective command.
This is the code of microbit
from microbit import *
uart.init(baudrate=57600, bits=8, parity=None, stop=1, tx=None, rx=None)
while True:
if button_a.is_pressed():
uart.write("Up")
display.show(Image.ARROW_NW)
if button_b.is_pressed():
uart.write("Down")
display.show(Image.ARROW_S)
else:
display.show(Image.ASLEEP)
This is the code of my python end
import re
import serial
import keyboard
serialPort = serial.Serial(port = "COM5", baudrate=57600,
bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
serialString = ""
while(1):
(serialPort.in_waiting > 0)
serialString = serialPort.readline()
wordsa = ("up")
wordsb = ("down")
if():
words = [word.lower() for word in wordsa if re.match('^[a-zA-Z]+', word)]
keyboard.press_and_release('up')
The problem is I want to have re to match the string or data received from microbit through uart at serialString = serial.Port.readline(), if the microbit sends UP, I would want python to match the data received is UP or Down, then press the keyboard key UP or DOWN respectively. Upon running this shitty code of mine, there are no errors showing up and it won't work at all. I think this is a very stupid question to ask, but please help me. This problem has burned a hole at my brain already.
Thank you and Kudos to DarryIG, Profile Link. He saved my days
If any beginners like me just wanting to do a match-up on a string.
You don't need to use regular expression. You can do it with operator == while = is assignment.
For example:
Game = ['Dota2', 'LoL']; #Games that you play
Like = ['Dota2', 'LoL']; #Games that your friend likes
if Game == Like:
print ('True')
else:
print ('False')
Output : True
Note: I know my answer sucks, but I just wanna keep this question answered just in case someone like me will need this information. Thanks for understanding.
Related
I'm playing with an remote console that asks me to return every word it gives.
For example :
>>> car # Remote console gives a word
car # I answer
Ok next word ! # Remote console after checking
>>> house # Remote console gives a second word and is waiting for me
I could manually answer each word the console says. But I'd like to make a script to automate it.
I'm thinking about a loop that would do this job, that is to say :
get the word from the remote console
send that word back to the remote console
I tried it with the pwntools Python library by using the recvline() and sendline() commands. I wrote :
import pwn
import re
c = pwn.remote ("URL", port)
question = str(c.recvline())
c.sendline(question)
c.interactive()
By doing this, the console returns :
Ok next word !
>>> house
That's a start but obviously as there's no loop, the script can't send "house" back. To adapt it, I used while and for loops on the recvline command but without results after many tries. And I must admit I'm getting stuck.
Is there a trick to do it and put each try inside the >>> input of the service ?
Any help would be very appreciated.
Thanks.
Hello I'm new to programming and I'm having a hard time in giving giving an assigned key to directions.
import random
move = [
"Left!",
"Right!",
"Forward!",
"Backward!",
"Accelerate!",
"Stop!",
]
direction = random.choice(move)
print(direction)
drive = input("[keypad]> ")
What I want to do is for example if the chosen random word is "Left!" then if I click "a" for left then the program would recognize it as correct answer and feed another direction to me.
Any suggestion to my problem would greatly help me. Thank you!
You'd have to put the input in a loop for it to keep asking the user for the key. There are other ways of getting input without having to use input as that stops your entire program. I recommend looking into the keyboard library for python (https://pypi.org/project/keyboard/)
I am trying to create a program that will constantly listen for speech, and if I say a certain string, it will call a certain function, example, if (string) then (function). I initially tried using Google Speech to Text API but could not get it to continuously listen (I even found a thread where someone said that Google Speech to Text API does not support continuous listening), so I reverted to PocketSphinx.
I have barely any code at all. I just have the initial beginner code you try out when you first install and run PocketSphinx (because I am a beginner). However, I don't want to do much. I created my own dictionary of a whopping 1 words, because I only want it to do one thing, and it reads it fine.
The problem I am having is actually using the string value that it constantly listens for to run future code. I don't know if I would have to add code to make it stop listening for a few moments after it hears a word in order for it to do something with the word is just heard or.... Also, I've heard that when you are comparing strings, you would use .equals() rather than ==, correct me/elaborate if I'm wrong. I've tried it both ways. When I use ==, nothing happens, it just continuously listens and prints the one word I say. When I use .equals(), I get an AttributeError.
First Method:
import os
from pocketsphinx import LiveSpeech, get_model_path
speech = LiveSpeech(
sampling_rate = 16000,
hmm=os.path.join(get_model_path(), 'en-us'),
lm='A:...(some random directory to a .lm file)',
dic='A:...(some random directory to a .dic file)')
for code in speech:
print(code)
if code == "string":
print("It works!")
Second Method:
import os
from pocketsphinx import LiveSpeech, get_model_path
speech = LiveSpeech(
sampling_rate = 16000,
hmm=os.path.join(get_model_path(), 'en-us'),
lm='A:...(some random directory to a .lm file)',
dic='A:...(some random directory to a .dic file)')
for code in speech:
print(code)
if code.equals(myString): #myString is set to the word I say to it.
print("It works!")
Second Method Error:
'LiveSpeech' object has no attribute 'equals'
You need to use live speech as if it were an iterator (like a list)
for example:
for phrase in speech:
text = phrase.hypothesis()
Happy Friday. This puzzle is really a pain in my neck, any advice will be appreciated. Thanks a ton.
I am on Python 2.7 with Windows 7.
I send a piece of command to device via model-client model (im at client side) and wait for a response (charging status) from device. Then I would like to extract some value from the list of return. And BANG! Error pops out! "IndexError: list index out of range".
My Python code is in below:
def chrg_Test():
try:
self.s.send(getchar)
time.sleep(2)
except:
print 'Chrg cmd sent failed...'
print 'Start Chrg Test...'
result = self.s.recv(1024)
time.sleep(3)
ExtPwrPresent = (result.split('\n'))[11]
print 'ExtPwrPresent is: ', ExtPwrPresent
chrg_Test()
And the Error is:
ExtPwrPresent = (result.split('\n'))[11]
IndexError: list index out of range
Some other details: what is wired is , the error pops out like 50% or more. And rest time it works good. So it got some temper and on and off randomly which is like an annoying babe~ The correct output should be like:
Result list is:
getchar
Label,Value
FuelPercent,31
BatteryOverTemp,0
ChargingActive,0
ChargingEnabled,0
ConfidentOnFuel,0
OnReservedFuel,0
EmptyFuel,0
BatteryFailure,0
ExtPwrPresent,0
ThermistorPresent,1
BattTempCAvg,23
VBattV,14.42
VExtV,0.00
Charger_mAH,0
Discharge_mAH,200
ExtPwrPresent is: ExtPwrPresent,0
So far, the solution I tried is - turn off the server socket and turn it on again, then run this client code. It works most time, but I think it is just a temporary way, I bet there is some better way to solve it.
I have a project that uses Python (2.* flavors) extensively and I am wondering if there is a terminal menu library or something to that effect? I am looking to breathe some flavor and life into my script by simplifying some of the options using arrow key highlightable options, some color, etc etc. I vaguely recall there being a way to make a bash shell terminal menu but I'm not at all sure how I would pass user input from bash to the python script, perhaps have a bash terminal menu push the script call with sysarggs? I'd like something on the python side if possible. Any suggestions?
Also just a random question, kind of fits in here since we're on the topic of terminal aesthetics, what's the best way to handle a counter? My script looks for image files, then when it finds one it clears the terminal with a subprocess call to clear and then prints the total images found again IE 10 images, find one, clear, print "11 images found", sometimes my script works REAL fast and I feel this detriments performance. Thoughts?
Thanks so much everyone, I love stack overflow ;)
Edit - Thanks for all the quick responses! I have alot of options to mull over. I gave everyone an upvote because all of your responses are helpful. I will check out all the libraries when I get home and try to pick one of you for an answer depending on what hashes out the best, wish I could pick you all though because all of your answers are relevant! Much appreciated folks. I'll report back in once I get home from work and get a chance to get some coding in ;)
Edit 2 - A clarification on the counter/progress display, looking for a way to keep this from detrimenting performance when my script finds thousands of images in a very short ammount of time, this is real chopped up python...
for each item in list:
if item ends with .jpg
cnt=cnt+1
do stuff with image file
subprocess.call('clear')
print str(cnt)+" total images processed."
Thanks again!
Check out Clint (*C*ommand *L*ine *IN*terface *T*ools)!
Official page: https://github.com/kennethreitz/clint
Great overview: http://www.nicosphere.net/clint-command-line-library-for-python/
Example colors:
from clint.textui import colored
print 'I love ' + colored.yellow('pyt') + colored.blue('hon')
and indents too:
from clint.textui import colored, indent, puts
with indent(3, quote=colored.red(' >')):
puts ('some random text')
puts ('another text')
with indent(3, quote=colored.green(' |')):
puts('some more nested identation')
puts('cool isn\'t?')
P.S. The same author wrote a similarly nice HTTP request library called "requests": https://github.com/kennethreitz/requests
If you want a lot of control and you're on *nix, you could use the stdlib curses module.
If you just want a bit of color (/don't want to modify your script a ton to fit curses), you can use ANSI escape codes. For example:
print '\033[1;32mgreen\033[1;m'
will print the word 'green' colored... green.
Here's a loading bar I came up with using carriage returns (based on the answers in this forum):
from time import sleep
import sys
num = 100
print 'Loading: [%s] %d%%' % (' '*(num/2), 0),
try:
colorCode = 43
for x in xrange(num+1):
if x == num: colorCode = 42
print '\rLoading: [\033[1;%dm%s\033[1;m%s] %d%%' % (colorCode, "|"*(x/2), " "*(num/2-x/2), x),
sys.stdout.flush()
sleep(0.02) # do actual stuff here instead
except KeyboardInterrupt:
print '\rLoading: [\033[1;41m%s\033[1;m%s] %d%% ' % ("|"*(x/2), " "*(num/2-x/2), x)
Example Output:
Loading: [||||||||||||||||||||||||||||||||||||||||| ] 82%
(Although it doesn't show up on SO, it is colored- yellow for loading, red for abort, and green for done.)
There's a library called Urwid that offers menus and some more. I never used it for serious purposes, but the it work pretty fine with my preliminary experiences on it. It works on Un*x systems only though. (The project page says it works under Cygwin, but I never tried.)