Python GCSE - Using Lists - python

In the next few weeks, I will be doing a computer science GCSE. I really need this GCSE as I aspire to because an Application Developer, so any help would be amazing! For the coding part of my GCSE, I need to create a python script that allows the user to type a string and then search for a word within that string. From there, the script would have to return all of the positions of that searched word. I have some example code here:
userinp = input("Please type a sentence: ")
list1[]
string1 = userinp.split()
for x in string1:
list1.insert(x,string1[x])
search = input("Search for a word: ")
for x in range(len(string1)):
if search in list1:
print("Word found at index:",x)
Please bare in mind this code may not work 100% as this was typed on a phone.
The actual task is to recall all of the positions of the words but after countless tries of trying, I cannot make it print the other indexes of the same word. For example, if the string was "Hello my name is Jack and my favourite food is apples" and I searched 'my', the program would have to return that the word was found at indexes 2 and 7.
As this was typed on a phone, the actual question may not have come out clear, if that is the case, please just comment saying so. Otherwise, any help would be amazing!

Try this,
userinp = raw_input("Please type a sentence: ")
words = userinp.split(' ')
search = raw_input("Search for a word: ")
for idx, word in enumerate(words):
if search == word:
print("Word found at index:", idx)
Hope it helps.

Related

Chatbot in python generates random answers if the userinput contains more than one word

My problem is, that my program randomly generates a random answer if the userinput contains more than one word, even though i don't want to. I mean i understand why the programm generates a random answer, but how can i overcome this?
Here is my code:
import random
print("Welcome to Chatbot! Have fun.")
print("")
randomanswer = ['Thats not good', 'me too', 'how about you?']
reactionanswer = {'hello': 'hello, whats up?',
'sad': 'speak to me',
'entertainment': 'how can i entertain you?'}
userinput = ''
while True:
userinput = input("Question/Answer: ")
userinput = userinput.lower()
if userinput == 'bye':
print("See you soon!")
break
else:
usersplit = userinput.split()
for i in usersplit:
if i in reactionanswer:
print(reactionanswer[i])
else:
print(random.choice(randomanswer))
Works fine for me, I ran exactly your code and get this:
Question/Answer: hello guy
hello, whats up?
Thats not good
Question/Answer: nothing in the list
me too
me too
me too
Thats not good
work also for several words. it depend on what works meaning - you wrote that for each word that not in your known list it would generate random answer. and for any known word it will answer as you want to. and that exactly what happen - in the first case the first word generated the first known answer and the second generated random answer. clarify what exactly not work as you expect.
The problem is that even though you found your answer the for loop continues to run. Add add "break" statement if the word has been found in answers. Like this:
else:
usersplit = userinput.split()
for i in usersplit:
if i in reactionanswer:
print(reactionanswer[i])
break < --- add this
else:
print(random.choice(randomanswer))

Python - If a "good" word and a "bad" word contains in a letter, print it out

I have a Bad word of list and a Good word to list. My idea was to make a first search for Good words and see which meaning in a letter contains those good word but if that meaning also contains a bad word - then it shouldn't print out the meaning.
etc:
Good word: "Lo", "Yes"
Bad word: "Hate", "Not"
text_roman: "Hello guys. My name is Lo and I hate to code :')"
Meaning: "Hello guys. My name is Lo and I hate to code :')" <-- "Just a joke!!
So meaning if it search for that meaning it should tell us there is a meaning that contains good and then check if it contains Bad word. If it does then we don't want to print out the meaning but if it doesn't contain any bad word then we should print it out.
How I tried to code was:
text_roman = "Hello guys. My name is Lo and I hate to code :')"
good_word = ["Lo", "Yes"]
bad_word = ["Hate", "Not"]
for text in good_word:
if text in text_roman:
print("Yay found word " + text_roman)
for bad_text in bad_word:
if bad_text not in text_roman:
print("Yay no bad words!")
When I tried this, the output gave all the words that contains the bad words aswell unfortunately
I would loop over the bad words first, and skip them. Then, if not skipped, check for a good word
good_word = ["Lo", "Yes"]
bad_word = ["Hate", "Not"]
has_bad = False
for b in bad_word:
if b in text_roman:
has_bad = True
continue
for g in good_word:
if g in text_roman:
print("Yay found word " + g + " in text_roman")
if not has_bad:
print("Yay no bad words!")
Note: in is case sensitive, so "Hate" in "I hate case-sensitivity" will be False

How to use dictionary to verify against user input?

So i wanted to make a little bot that could hold a small conversation with a user. The only problem is that when i type one of the words in the list(being hello or hi) then i get the welcome user message, but if i type something like hello computer it gives me the TESTPHRASE message. Is there something i can put in so that it looks in the sentence of the user input and finds a word in the used list so that it can say the appropriate response.
user_greetings = {"hello", "hi"}
user_input = input("-")
if user_input in user_greetings:
print("Welcome User")
else:
print("TESTPHRASE")
When you apply in to a string and a dictionary, it will test if the entire string is a key. It looks like you want to check for either the first word in the sentence or any word in the sentence being in the dictionary.
In either case, you'd want to split the input on spaces:
words = input('-').split()
If you want to check the first word, proceed almost as before:
if words[0] in user_greetings:
print("Welcome User")
else:
print("TESTPHRASE")
If any of the words should trigger the welcome message, use any and a generator expression:
if any(x in user_greetings for x in words):
print("Welcome User")
else:
print("TESTPHRASE")
I'm getting a syntax error for your code. Try moving else to it's own line. Otherwise, your code works for me.
EDIT:
Reread the question. Your code is checking if "hello computer" is in greetings, which is {'hello', 'hi'}. "hello computer" is not in greetings. You could reverse the search and do
for greeting in user_greetings:
if greeting in user_input:
# print greeting
Otherwise, you need to add "hello computer" to your list of greetings.
Something like this would do it:
greetings = ['hello', 'hi']
input = 'hello computer'.split()
if set(greetings).intersection(set(input)):
print('Welcome')
#Mad Physicist gives a very comprehensive answer for this and I upvoted his answer.
There is another way of doing it if any word will trigger the welcome message, no matter it is capitalized or not.
user_greetings = {"hello", "hi"}
user_input = input("-").split()
# set process control.
greeting = None
for word in user_input:
if word.lower() in user_greetings:
print("Welcome User")
else:
greeting = True
if greeting:
print("TESTPHRASE")

Using conditionals to find words in strings

I am currently attempting to make a program that will help a user repair their phone depending on an input they type in
I have an issue where if someone were to answer that their screen is not working it will print the solution to two answers.
import string
punct = set(string.punctuation)
sentence = input('Please enter what is wrong with your phone ').lower()
sentence2 = ''.join(x for x in sentence if x not in punct)
if 'smashed' and 'screen' in sentence2:
print ('Send your phone off for repairs')
if 'screen' and 'not' and 'working' in sentence2:
print ('Charge your phone')
Here is my error:
To check that a set of key words are all found in a sentence, you need to use if word1 in sentence and word2 in sentence, or if all(...):
diagnosis = {
'Send your phone off for repairs': ['smashed', 'screen'],
'Charge your phone': ['screen', 'not', 'working']
}
for solution, words in diagnosis.items():
if all(word in sentence for word in words):
print(solution)

Searching for key words in python

If I ask a question in Python and the answer is chicken, I want to output something related to chicken. And, if the answer is beef I want to output something related to beef, dependent on the answer provided.
How could I structure this? Should I have multiple lists with key words and related answers? Newbie.
I would use a dict of lists:
import random
similar_words = {
'chicken': ['poultry', 'wings'],
'beef': ['cow', 'ground-beef', 'roast-beef', 'steak'],
}
word = raw_input("Enter a word: ").strip()
if word in similar_words:
print random.choice(similar_words[word])
else:
print "Not found!"
See the Python manual on Data Structures for more information. Note that I'm also using random.choice() to select a random item from each list.
Here's the output of it running:
$ python words.py
Enter a word: chicken
poultry
$ python words.py
Enter a word: beef
cow
$
Edit: You were asking in the comments how you could do this if the words were contained inside a whole sentence. Here's one example:
words = raw_input("Enter a word or sentence: ").strip().split()
for word in words:
if word.lower() in similar_words:
print random.choice(similar_words[word.lower()])
else:
print "Not found!"
Here, we're using split() to split the sentence into a list of words. Then we loop through each word, and see if (the lowercase version of) the word exists in our dict, and do the same thing as we did above with a single word.

Categories