Replacing Multiple lines of Console Text Python 2.7 - python

So i am creating a slot machine as a little project for fun and learning, I was wondering if there was a way to replace multiple lines of text in the console. I have it replacing one line but I would like to be able to print three lines then the top be replaced with the middle then middle with the bottom and continue untill the loop is finished. I am still a beginner so if there are any tips you have for me and or please feel free to critique my code. Thank you
import sys
import time
from random import randint
slot_possibilities = [" Star "," Moon "," Sun! "," Monkey"]
wait_time = 15
print "--------------------------------"
print "|--------Monkey-----Slots------|"
print "|------------------------------|"
while wait_time != 0 :
x = randint(0,3)
y = randint(0,3)
z = randint(0,3)
sys.stdout.write("\r|" + slot_possibilities[x] + " || " + slot_possibilities[y] + " || "+ slot_possibilities[z] + " |")
time.sleep(1)
wait_time -= 1
print
print

Related

Why is wikipedia.summary(string) removing letters from my string?

I am working on a program that can search wikipedia given an input like: "Who is Elon Musk" - however, with his specific example (and others), when the variable is placed into wikipedia.summary(string), it removes the "l" in "Elon Musk". Attached is my function:
import wikipedia
import spacy
def search_wiki(self, search):
nlp = spacy.load('en_core_web_sm')
doc = nlp(search)
subject_phrase = get_subject_phrase(doc)
try:
results = wikipedia.page(str(subject_phrase)) #removes here
final = results
print(wikipedia.summary(final, sentences=1))
except wikipedia.exceptions.PageError:
results = wikipedia.search(str(subject_phrase))
print("\nDid you mean " + results[0] + "?\n")
possible = results[0]
if input() == "yes":
final = possible
print(final) #prints "Elon Musk"
print(wikipedia.summary(final, sentences=1)) #removes here too
else:
print("\nThese are the other searches that came up for " + str(subject_phrase) + ":\n")
for r in results:
print(r)
print("\nPlease type the result you want me to search for:\n")
final = input()
print(wikipedia.summary(final, sentences=1))
except wikipedia.exceptions.DisambiguationError as e:
print("I couldn't find anything for " + str(subject_phrase) + ". Here are some related results:")
for o in e.options:
print(o)
print("\nWhich of these did you mean?")
final = input()
print(wikipedia.summary(final, sentences=2))
print("\nWould you like to hear more about " + final + "?\n")
if input() == "yes":
print("\nYou can read more about " + final + " at " + wikipedia.page(final).url + "\n")
entry = wikipedia.summary(final, sentences=3)
return lambda: entry, True
else:
entry = wikipedia.summary(final, sentences=1)
return lambda: entry, False`
I am pretty stuck, I have the variable printing right before the call to wikipedia.summary(string), so I know that the variable is not changing on my end (or at least I think).

Win 10 not detecting mouse movement from Python code

I've written a small program that will move the cursor every 5 seconds if it has not been moved.
I've provided the code below.
But it seems that no matter how much I move it, Windows 10 does not recognise it's movement.
To speed up the testing, I've set Turn Off display to 1 min in the Power plan settings. When this code it run through the CMD, I can see the mouse moving back and forward, but the screen still goes to sleep after 1 min.
Is there something I'm missing here?
Thank you
#! python3
import pyautogui as p
import time as t
# CTRL+C to stop it
p.FAILSAFE = False
try:
while True:
# get current mouse position
x1,y1 = p.position()
positionStr1 = 'X: ' + str(x1).rjust(4) + ' Y: ' + str(y1).rjust(4)
print("check1")
print(positionStr1, end='')
print("\n")
# wait 5 sec
t.sleep(5)
#check the position again
x2,y2 = p.position()
positionStr2 = 'X: ' + str(x2).rjust(4) + ' Y: ' + str(y2).rjust(4)
print("check2")
print(positionStr2, end='')
print("\n")
if positionStr1 == positionStr2:
p.moveRel(200,0, duration=.1)
p.moveRel(-200,0,duration=.1)
p.moveRel(200,0, duration=.1)
p.moveRel(-200,0,duration=.1)
else:
print('mouse moved')
except KeyboardInterrupt:
print('\nDone')

Using random.choice to print two words from a random line in a file

I'm currently making a music quiz game and I'm trying to select a random line and print the 2 variables I've already assigned in that line, however I can't find a good way to do this. Bellow you can see what I've done so far along with how linked 2 variables per line in the file. Thanks for any help!
This is how I'm adding variables to the different lines
Artist='Cold Play';Song1='Clocks'
file.write(Artist + " " + Song1 + "\n")
Artist='Beatles';Song1='Revolution'
file.write(Artist + " " + Song1 + "\n")
Artist='Pharrel Williams';Song1='Happy'
file.write(Artist + " " + Song1 + "\n")
Artist='Owl City';Song1='Fireflies'
file.write(Artist + " " + Song1 + "\n")
Artist='Oasis';Song1='Wonderwall'
file.write(Artist + " " + Song1 + "\n")
file.close()
This Is the bit I'm stuck with
Song = (random.choice(open("SongFile2.txt").read().split()))
print("Please type yes to continue playing")
print("or type something random to recieve a nice message and quit the
game")
PlayerAnswer = input()
if PlayerAnswer == ("yes"):
print("Question:" + str(Question))
print("" + Song1[0] + ": This is the first letter of the song" )
print("The Artist is: " + Artist)
print("Now guess the Song (Remember to use capital letters for
Names)")
PlayerGuess = input()
What I want is for the program to output the first letter of a song and the Artist associated with the song from a random line of the file
You should switch the way to store your data - use a seperator character between artist and song that does not occur in either one.
A '|' is a good divider for songs and artists. You can use it like so:
Write data file:
# use a seperator character between artist and song that does not occur in either
with open("songs.txt","w") as f:
f.write('''Cold Play|Clocks
Beatles|Revolution
Pharrel Williams|Happy
Owl City|Fireflies
Oasis|Wonderwall''') # write a multiline-file
Game:
import random
def get_all_music():
"""Load music from songs.txt and return as list of 2-elem-lists.
Lines not containing | are ignored."""
with open("songs.txt") as f:
return [x.strip().split("|") for x in f.readlines() if '|' in x]
all_music = get_all_music()
for _ in range(3):
artist, song = random.choice(all_music)
print("Song starting with '{}' by '{}'.".format(song[0],artist))
s = input("What is it's name?")
if s == song:
print("Correct!")
else:
print("'{}' is wrong. It was '{}'".format(s,song))
Output:
Song starting with 'C' by 'Cold Play'.
What is it's name? Clocks
Correct!
Song starting with 'F' by 'Owl City'.
What is it's name? Clocks
'Clocks' is wrong. It was 'Fireflies'
....
The read() method returns the entire file contents as one long string, which makes it harder to pick out a random song. Try using readlines() instead, which returns each line in the file in a list, making it much easier to use random.choice().
And as others have said, using a space to separate the artist and song title makes it much harder to tell where the artist name ends and the song title begins, because the artist and song title can also contain spaces.
You could do something like this to get a random line:
import random
with open("file.txt","r") as f:
list_of_lines = f.readlines()
list_of_indexes = list(range(len(list_of_lines)))
rand_index = random.choice(list_of_indexes)
random_line = list_of_lines[rand_index]
When you get the random line use regular expressions to get the desired elements. This is a useful site to test your regular expression:
https://regex101.com/

Python Multiprocessing - Too Slow

I have built a multiprocessing password cracker (using a wordlist) for a specific function, it halved the time needed compared to using a single process.
The original problem being that it would show you the cracked password and terminate the worker, but the remaining workers would carry on until they ran out of words to hash! not ideal.
My new step forward is to use Manager.Event() to terminate the remaining workers, this works as I had hoped (after some trial and error), but the application now takes far longer that it would take as a single process, I'm sure this must be due to the if function inside pwd_find() but I thought I would seek some advice.
#!/usr/bin/env python
import hashlib, os, time, math
from hashlib import md5
from multiprocessing import Pool, cpu_count, Manager
def screen_clear(): # Small function for clearing the screen on Unix or Windows
if os.name == 'nt':
return os.system('cls')
else:
return os.system('clear')
cores = cpu_count() # Var containing number of cores (Threads)
screen_clear()
print ""
print "Welcome to the Technicolor md5 cracker"
print ""
user = raw_input("Username: ")
print ""
nonce = raw_input("Nonce: ")
print ""
hash = raw_input("Hash: ")
print ""
file = raw_input("Wordlist: ")
screen_clear()
print "Cracking the password for \"" + user + "\" using "
time1 = time.time() # Begins the 'Clock' for timing
realm = "Technicolor Gateway" # These 3 variables dont appear to change
qop = "auth"
uri = "/login.lp"
HA2 = md5("GET" + ":" + uri).hexdigest() # This hash doesn't contain any changing variables so doesn't need to be recalculated
file = open(file, 'r') # Opens the wordlist file
wordlist = file.readlines() # This enables us to use len()
length = len(wordlist)
screen_clear()
print "Cracking the password for \"" + user + "\" using " + str(length) + " words"
break_points = [] # List that will have start and stopping points
for i in range(cores): # Creates start and stopping points based on length of word list
break_points.append({"start":int(math.ceil((length+0.0)/cores * i)), "stop":int(math.ceil((length+0.0)/cores * (i + 1)))})
def pwd_find(start, stop, event):
for number in range(start, stop):
if not event.is_set():
word = (wordlist[number])
pwd = word.replace("\n","") # Removes newline character
HA1 = md5(user + ":" + realm + ":" + pwd).hexdigest()
hidepw = md5(HA1 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2).hexdigest()
if hidepw == hash:
screen_clear()
time2 = time.time() # stops the 'Clock'
timetotal = math.ceil(time2 - time1) # Calculates the time taken
print "\"" + pwd + "\"" + " = " + hidepw + " (in " + str(timetotal) + " seconds)"
print ""
event.set()
p.terminate
p.join
else:
p.terminate
p.join
if __name__ == '__main__': # Added this because the multiprocessor module sometimes acts funny without it.
p = Pool(cores) # Number of processes to create.
m = Manager()
event = m.Event()
for i in break_points: # Cycles though the breakpoints list created above.
i['event'] = event
a = p.apply_async(pwd_find, kwds=i, args=tuple()) # This will start the separate processes.
p.close() # Prevents any more processes being started
p.join() # Waits for worker process to end
if event.is_set():
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
else:
screen_clear()
time2 = time.time() # Stops the 'Clock'
totaltime = math.ceil(time2 - time1) # Calculates the time taken
print "Sorry your password was not found (in " + str(totaltime) + " seconds) out of " + str(length) + " words"
print ""
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
Edit (for #noxdafox):
def finisher(answer):
if answer:
p.terminate()
p.join()
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
def pwd_find(start, stop):
for number in range(start, stop):
word = (wordlist[number])
pwd = word.replace("\n","") # Removes newline character
HA1 = md5(user + ":" + realm + ":" + pwd).hexdigest()
hidepw = md5(HA1 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2).hexdigest()
if hidepw == hash:
screen_clear()
time2 = time.time() # stops the 'Clock'
timetotal = math.ceil(time2 - time1) # Calculates the time taken
print "\"" + pwd + "\"" + " = " + hidepw + " (in " + str(timetotal) + " seconds)"
print ""
return True
elif hidepw != hash:
return False
if __name__ == '__main__': # Added this because the multiprocessor module sometimes acts funny without it.
p = Pool(cores) # Number of processes to create.
for i in break_points: # Cycles though the breakpoints list created above.
a = p.apply_async(pwd_find, kwds=i, args=tuple(), callback=finisher) # This will start the separate processes.
p.close() # Prevents any more processes being started
p.join() # Waits for worker process to end
You can use the Pool primitives to solve your problem. You don't need to share an Event object which access is synchronised and slow.
Here I give an example on how to terminate a Pool given the desired result from a worker.
You can simply signal the Pool by returning a specific value and terminate the pool within a callback.
I think your hunch is correct. You are checking a synchronization primitive inside a fast loop. I would maybe only check if the event is set every so often. You can experiment to find the sweet spot where you check it enough to not do too much work but not so often that you slow the program down.

Why is 'module' object not callable? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
TypeError: ‘module’ object is not callable
This is my very first Python attempt, just trying to regain basic programming knowledge after a 10 year silence in a, for me, new language, Python. The basic idea is a tiny battly engine which decides the better hit. The bugging code is next.
self.__power = self.__att*random(2,4)/dier.__defn
As my python knowledge is extremely basic, I'm rather scared of saying the right things so Im gonna put my code down below (47 lines), you..ll notice it is really transparant so I dont suspect this will give any problem. The errorline is 16. I tried renaming the att variable to atta as well as some repositionings though new bugs come, I solve them and in the end its always the same error on the same line.
class Character:
def __init__(self,name="", att=0,defn=0,lvl=0,leven=0,exp=0, power=0):
self.__att = att
self.__defn = defn
self.__lvl = lvl
self.__leven = leven
self.__name = name
self.__xp = exp
self.__power = power
def batl(self):
import random
while self.__lvl <= 3:
dier = Character("Anaconda",1,1,50,1,0,0)
print "You encountered an " + dier.__name + " and fight it."
**self.__power = self.__att*random(2,4)/dier.__defn**
dier.__power = (dier.__att*random(1,4))/self.__defn
if self.power > dier.power:
growth = dier.__lvl*dier.__atta
groei()
else:
dmg = dier.lvl*dier.att
leven = leven-dmg
if leven < 0:
print "Alas, you're done for."
exit()
else:
print "You took " + dmg + "damage and have " + leven + "life left."
def groei(self):
if (growth+exp) > 100:
lvl += 1
exp = growth-100
print "You won and gained " + str(growth) + " and grew from level " + str(lvl-1) + " to level " + str(lvl) + "."
else:
exp = growth + exp
print "You won and gained " + str(growth) + "."
def main():
hero = Character("Nevery",2,1,2,100,0,0)
hero.batl()
if name == 'main':
main()
As you can see ive got my character class, in which i have defined the battle() method and the groei() method, very basic. Can anyone point me what I'm missing out on, been looking at it for hours. Thanks in Advance
random is the module, not the function. You need to call random.random. You could also from random import random, but I'd go with the first option in this case.
Use random.random() instead of random?

Categories