Keyboard inputs within a while loop with multiple options - python

I am writing a code that takes a user inputted word or phrase, and then returns a string of the 50 words before and after the given word. I want it to be able to scroll through the instances where that word or phrase is found by pressing the space bar to continue, or any other button to quit. The problem that I'm running into is that if I use the keyboard.wait() method I can only allow for one type of user input, but if I use any of the other keyboard methods that I have tried it doesn't stop my while loop and accept input. Here is the code I'm currently working with, any ideas would be helpful.
while True:
keyboard.wait(" "):
x = (x+1)%len(where_found)
context = contents[where_found[x]-50:where_found[x]+50]
context = " ".join(context)
print(context+"\n")
where_found is a list containing all the index positions of the word that was searched for, or the first word if it was a phrase.
content is a list created with the read().split() method of file reading.
x is assigned a value of 1 before this section of code and allows the code to cycle through the instances where it was found.
Edit:
I have tried both readchar.readkey() and msvcrt.getch() with no success. When they are reached my shell responds as if it is waiting for an input, but never actually accepts one. I am using windows and python 3.8.5.

I tried to use keyboard.readkey from https://github.com/boppreh/keyboard but it kept returning two lines on each keypress.
Following a comment in this answer, here is a solution with https://github.com/magmax/python-readchar
It's API is a lot simpler and (on windows) it does not seem to have problems with blocking.
(contents.txt has the text from this question)
import readchar
with open('contents.txt', 'r') as fo:
contents = fo.read().split()
word = input('Please write a word to be searched: ')
print('\n### Press space for next match, any other key to exit\n')
print('matches found:')
x = -1
delta = 5
while True:
try:
x = contents.index(word, x+1)
context = ' '.join(contents[max(x-delta, 0):x+delta+1])
print(context)
if readchar.readkey() != ' ':
print('\n\nShutting down...')
break
except:
print('\n\nthere are no more matches')
break
Testing in terminal.
It waits for a keypress, I pressed only spaces.
Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
of the 50 words before and after the given word. I
doesn't stop my while loop and accept input. Here is the
before this section of code and allows the code to cycle
there are no more matches
Testing with other keys
Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
of the 50 words before and after the given word. I
You pressed '\r'
Shutting down...
Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
You pressed 'd'
Shutting down...

Related

Keeping track of position in searched text when the same word appears more than once

def test():
users_note = """There is a substantial need for child mental health support –
evidence shows that at any given year,
1 in 10 young people will have a diagnosable mental health problem.
Out of these incredibly high numbers,
70% of these young people do not receive adequate mental health support at all,
and of the 30% that do,
only half of them improve.
Though we have evidence-based intervention techniques that work,
we are still relying on outdated technologies and delivery mechanisms.
"""
note_list = users_note.split()
while True:
for users_try in range(5):
word_list = input('Enter words you gonna say next: ').split()
for word in word_list:
if word not in note_list:
print('Sorry, try again')
else:
print(note_list[note_list.index(word) + 1])
else:
break
This function is essentially a teleprompter. When the user inputs a word or multiple words in any order, the function prints the word right after each of the user's input words. However, there's an edge case when an input word occurs multiple times within the pre-made text; the function always prints the word the first occurrence. How can this function be modified in order to keep track of the user's input word position within the pre-made text? For example:
For the first occurrence of "a" in the pre-made text:
Enter words you gonna say next: a
substantial
If the user has already passed that point in the text, inputting "a" a second time:
Enter words you gonna say next: a
diagnosable
For the first occurrence of "these" in the pre-made text:
Enter words you gonna say next: these
incredibly
If the user has already passed that point in the text, inputting "these" a second time:
Enter words you gonna say next: these
young
In other words, the program should continue moving forward in the text once a word has already been searched for. How do I accomplish that?
As long as you don't intend for the user to ever be able to go backwards in the text, an easy solution is to modify note_list as you go:
if word not in note_list:
print('Sorry, try again')
else:
note_list = note_list[note_list.index(word) + 1:]
print(note_list[0])
This makes it impossible to ever "repeat" a particular word, whether the word is unique or not.

The break statement - Stuck in a loop [duplicate]

This question already has answers here:
Python Programming Unintentional Infinite Loop
(2 answers)
Closed 5 years ago.
Objectives
Familiarize the student with:
- using the break statement in loops;
- reflecting real-life situations in computer code.
Scenario
The break statement is used to exit/terminate a loop.
Using the while loop, design a program that continuously asks the user to enter a secret word (e.g.,"You're stuck in an infinite loop! Enter a secret word to leave the loop:") unless the user enters "chupacabra" as the secret exit word, in which case the message "You've successfully left the loop" should be printed to the screen, and the loop should terminate.
Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement.
'''
Lab 2.2.22.1 - While loops with 'break' keyword use.
'''
secret_word = str(input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop."))
while secret_word != "chupacabra":
print("You're stuck in an infinite loop!\nEnter a secret word to leave the loop.")
if secret_word == "chupacabra":
print("You've successfully left the loop.")
'''
just keeps printing out both lines continuosly - in a loop.
'''
Problem
When I run this program, it prints the first 2 lines and waits for an input. If the input matches the var, it doesn't display the "left the loop" string, it just does nothing. If I enter anything other than the correct secret word, it just keeps on printing in a never ending loop those first two lines again.
I'm stuck on how to use the while loop. I only want to do 2 things, print A if the input does not equal the var, and print B if the input does match the var. But everything I've read about the while loops is giving the while something to do, then the if or elif or else get something else to do each.
I'm struggling with this because I don't know how to write this loop so that while doesn't have to do anything, does this make sense?
I'm doing a python course atm, so please bear with me. This is not part of any exams or graded work, but I would rather understand what I'm doing wrong first please.
You need to read for secret_word in loop, and use break to exit when it matches wanted :
secret_word = ""
while True:
secret_word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop.")
if secret_word == "chupacabra":
print("You've successfully left the loop.")
break

How to fix this Anagram Scrambler code?

print "YOU HAVE CHOSEN TO REARRANGE YOUR THE WORD THAT YOU ARE ABOUT TO ENTER..."
word = raw_input ("FIRSTLY YOU MUST ENTER A WORD TO BE REARRANGED, ENTER IT HERE:")
character_save = word[1]
def anagram(word):
if len(word)>1:
print str.replace('a','b')
word = str.replace(word[1],word[3])
word= str.replace(word[3], character_save,1)
print word
anagram(word)
I tried to fix this on numerous occasions, the problem with the first time was that it would just replicate characters instead of replacing the positions, the second time I tried to store the position that I was going to replace in a variable but now it mentions that I have only one argument given (when it should be 2).
Would it be easier to do this with a list instead of a string?
The replace message that you are using is called on the string that you want to replace and not on the str type itself.
In your case that is the word parameter that you are providing.
So if you replace the instances of str.replace with word.replace your code will run. However, it doesn't create an anagram yet. The algorithm is still lacking.

Python - my while loop is stopping itself

This is a homework question and it asks "Pick a word. Ask the user to enter a letter. Check how many times the letter is present in your word and output the number on the screen." So far I have written it as is and it seems to be working fine:
word = str("python")
letters = len(word)
attempt = str(raw_input ("Enter a letter: "))
while attempt in word:
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
attempt = str(raw_input ("Enter another letter: "))
while attempt not in word:
attempt = str(raw_input ("This letter is not present, enter another letter: "))
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
but occasionally if I am inputting letters the program will stop and no longer take any more inputs. What am I doing wrong? I apologize if the code is very sloppy and poorly written as I am new to programming. Thanks.
I'm not sure if this is what you're getting at, but your while loops will execute one after the other. They don't both apply all the time. So the first while means "keep doing this as long as the user enters a letter that is in the word", and that loop will keep executing as long as the user enters letters in the word. As soon as the user enters one letter that isn't in the word, the loop will end and things will move on to the second loop. Execution will never go back to the first loop. Likewise, once in the second loop, if you then enter a letter that is in the word, the loop will end. Since that's the end of the program, the program will end.
So if you enter a letter that isn't in the word, then enter a letter that is in the word, the program will end. Like if you first enter "x" and then enter "y", it will then stop.
I think what you really want is more like:
while True:
attempt = raw_input("Enter a letter:")
if attempt in word:
print "That was in the word", word.count(attempt), "times"
else:
print "That was not in the word"
Of course, this program will loop infinitely until you close it by pressing Ctrl-Break or the like.
There are some other issues with your code. You don't need to wrap "python" in str, since that already is a string. You also don't need to wrap raw_input in a string, since raw_input already returns a string. You define a variable called letters but never use it.
Also, you define word = "python" at the beginning, but then sometimes later you use the word variable, while other times you retype the string "python" in your code. It doesn't matter for this program, but in general it's a good idea to assing the variable once and use that everywhere; otherwise you'll have to change it in many places if you decide to use a different word, which increases the likelihood that you'll forget to change it in one place, and thereby cause a bug.
Finally, note that in and count operate on substrings, not just single letters. So entering "yth" as as your input will still work and give a count of 1. There's not necessarily anything wrong with this, but you should be aware that although you're asking for letters the person can type in anything, and substrings of any length will still be found in the "word".
The program is sequential with two loops. Once those loops have been passed the program ends.
Loop 1: run while the input is found in the word.
As soon as this condition fails, we fall through to loop 2:
Loop 2: run while the input is not found in the word.
As soon as this condition fails, we fall through to the end of the program.
So, if you enter a "bad" input once, then a "good" input once, the program will end.
What you want to do is wrap both loops into one, and use an if-else to decide which each particular input is.

Finding specific words in a file

I have to write a program in python where the user is given a menu with four different "word games". There is a file called dictionary.txt and one of the games requires the user to input a) the number of letters in a word and b) a letter to exclude from the words being searched in the dictionary (dictionary.txt has the whole dictionary). Then the program prints the words that follow the user's requirements. My question is how on earth do I open the file and search for words with a certain length in that file. I only have a basic code which only asks the user for inputs. I'm am very new at this please help :(
this is what I have up to the first option. The others are fine and I know how to break the loop but this specific one is really giving me trouble. I have tried everything and I just keep getting errors. Honestly, I only took this class because someone said it would be fun. It is, but recently I've really been falling behind and I have no idea what to do now. This is an intro level course so please be nice I've never done this before until now :(
print
print "Choose Which Game You Want to Play"
print "a) Find words with only one vowel and excluding a specific letter."
print "b) Find words containing all but one of a set of letters."
print "c) Find words containing a specific character string."
print "d) Find words containing state abbreviations."
print "e) Find US state capitals that start with months."
print "q) Quit."
print
choice = raw_input("Enter a choice: ")
choice = choice.lower()
print choice
while choice != "q":
if choice == "a":
#wordlen = word length user is looking for.s
wordlen = raw_input("Please enter the word length you are looking for: ")
wordlen = int(wordlen)
print wordlen
#letterex = letter user wishes to exclude.
letterex = raw_input("Please enter the letter you'd like to exclude: ")
letterex = letterex.lower()
print letterex
Here's what you'd want to do, algorithmically:
Open up your file
Read it line by line, and on each line (assuming each line has one and only one word), check if that word is a) of appropriate length and b) does not contain the excluded character
What sort of control flow would this suggest you use? Think about it.
I'm not sure if you're confused about how to approach this from a problem-solving standpoint or a Python standpoint, but if you're not sure how to do this specifically in Python, here are some helpful links:
The Input and Output section of the official Python tutorial
The len() function, which can be used to get the length of a string, list, set, etc.
To open the file, use open(). You should also read the Python tutorial sec. 7, file input/output.
Open a file and get each line
Assuming your dictionary.txt has each word on a separate line:
opened_file = open('dictionary.txt')
for line in opened_file:
print(line) # Put your code here to run it for each word in the dictionary
Word length:
You can check the length of a string using its str.len() method. See the Python documentation on string methods.
"Bacon, eggs and spam".len() # returns '20' for 20 characters long
Check if a letter is in a word:
Use str.find(), again from the Python sring methods.
Further comments after seeing your code sample:
If you want to print a multi-line prompt, use the heredoc syntax (triple quotes) instead of repeated print() statements.
What happens if, when asked "how many letters long", your user enters bacon sandwich instead of a number? (Your assignment may not specify that you should gracefully handle incorrect user input, but it never hurts to think about it.)
My question is how on earth do I open the file
Use the with statement
with open('dictionary.txt','r') as f:
for line in f:
print line
and search for words with a certain length in that file.
First, decide what is the length of the word you want to search.
Then, read each line of the file that has the words.
Check each word for its length.
If it matches the length you are looking for, add it to a list.

Categories