Using conditionals to find words in strings - python

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)

Related

how to remove instances and possible multiple instances of a certain word in a string and return a string (CODEWARS dubstep)

I have had a go at the CODEWARS dubstep challenge using python.
My code is below, it works and I pass the kata test. However, it took me a long time and I ended up using a brute force approach (newbie).
(basically replacing and striping the string until it worked)
Any ideas with comments on how my code could be improved please?
TASK SUMMARY:
Let's assume that a song consists of some number of words (that don't contain WUB). To make the dubstep remix of this song, Polycarpus inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
# => WE ARE THE CHAMPIONS MY FRIEND
song_decoder("AWUBBWUBC"), "A B C","WUB should be replaced by 1 space"
song_decoder("AWUBWUBWUBBWUBWUBWUBC"), "A B C","multiples WUB should be replaced by only 1 space"
song_decoder("WUBAWUBBWUBCWUB"), "A B C","heading or trailing spaces should be removed"
Thanks in advance, (I am new to stackoverflow also)
MY CODE:
def song_decoder(song):
new_song = song.replace("WUB", " ")
new_song2 = new_song.strip()
new_song3 = new_song2.replace(" ", " ")
new_song4 = new_song3.replace(" ", " ")
return(new_song4)
I don't know if it can improve it but I would use split and join
text = 'WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB'
text = text.replace("WUB", " ")
print(text)
words = text.split()
print(words)
text = " ".join(words)
print(text)
Result
WE ARE THE CHAMPIONS MY FRIEND
['WE', 'ARE', 'THE', 'CHAMPIONS', 'MY', 'FRIEND']
WE ARE THE CHAMPIONS MY FRIEND
EDIT:
Dittle different version. I split usinsg WUB but then it creates empty elements between two WUB and it needs to remove them
text = 'WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB'
words = text.split("WUB")
print(words)
words = [x for x in words if x] # remove empty elements
#words = list(filter(None, words)) # remove empty elements
print(words)
text = " ".join(words)
print(text)

How to remove adjectives or attributive before noun?

Currently I am using nltk to remove all the adjectives, this is my attempt:
def remove_adj(sentence):
adjective_tags = ["JJ", "JJR", "JJS"]
tokens = nltk.word_tokenize(sentence)
tags = nltk.pos_tag(tokens)
for i in range(len(tags)):
word = [word for word,pos in tags if (pos not in adjective_tags)]
return ' '.join(word)
But what I need is different from this one. Here are some examples:
input: "who has the highest revenue" output: "who has the revenue"
input: "who earned more than average income" output: "who earned more than income"
input: "what is the mean of profit" output: "what is the profit"
Can anyone give me some suggestions? Thanks all in advance.
I think I understand what you are trying to achieve, but what problem are you having? I've run your code and it appears to work perfectly at removing adjectives.
A couple things are throwing me off though. For the below input/output, you can expect the word 'more' to be removed, as it is an adjective with token 'JJR'. Your post suggests that you were not expecting it to be removed.
input: "who earned more than average income" output: "who earned more than income"
Also, I'm not sure why you were expecting the word 'mean' to be removed in the below input/output, as it isn't an adjective.
input: "what is the mean of profit" output: "what is the profit"
A great place to check you sentences is Parts of Speech
Below would be your actual outputs, removing the adjectives correctly, and it seems to be doing just that.
input: "who has the highest revenue" output: "who has the revenue"
input: "who earned more than average income" output: "who earned than income"
input: "what is the mean of profit" output: "what is the mean of profit"
If you are simply trying to remove any descriptive elements pertaining to the noun, I would have to ask more about your problem. Your examples all ended with a noun, and this appears to be the noun you are focusing on. Will this be the case with all sentences that this code would handle? If so, you might consider iterating through your sentence backwards. You can easily identify the noun. As you step through, you would then look to see if the noun has a determiner (a, an, the) with tag 'DT', as you wouldn't want to remove that from what I see. You continue to step through removing everything until you reach an adjective or another noun. I don't know what your actual rules are for removing words on this one, but working backwards may help.
EDIT:
I tinkered with this a bit and got the below code to work exactly as you wanted on the outputs. You can populate tags in the 'stop_tags' variable if there are other speech tags you want it to stop on.
def remove_adj(sentence):
stop_tags = ["JJ", "JJR", "JJS", "NN"]
tokens = nltk.word_tokenize(sentence)
tags = list(reversed(nltk.pos_tag(tokens)))
noun_located = False
stop_reached = False
final_sent = ''
for word,pos in tags:
if noun_located == False and pos == 'NN':
noun_located = True
final_sent+=f' {word}'
elif stop_reached == False and pos in stop_tags:
stop_reached = True
elif stop_reached == True:
final_sent+=f' {word}'
final_sent = ' '.join(reversed(final_sent.split(' ')))
return final_sent
x = remove_adj('what is the mean of profit')
print(x)
`

Python Code to find the letter start with a in a sentence

Here is the code to find the words start with a in the sentence: "This is an apple tree."
st = 'This is an apple tree'
for word in st.split():
if word[0]=='a':
print(word)
I want to make it to function, and takes in any sentence I want, how to to that?
Here is the code I came up, but is not doing what I want.
def find_words(text):
for word in find_words.split():
if word[0]=='a':
print(word)
return find_words
find_words('This is an apple tree')
Thank you.
You can use the below code. It will provide the list of words which has a word starts with 'a'.
This is simple list comprehension with if clause. Split without argument by default splits the sentence by space and startswith method helps to filter 'a'.
sentence = 'This is an apple tree'
words = [word for word in sentence.split() if word.startswith('a')]
The problem is how you are defining the for loop. It should be:
for word in text.split(' '):
...
Just because text is the parameter in your defined function
If you want to print the result try this:
st = 'This is an apple tree'
def find_words(text):
for word in text.split():
if word.startswith('a'):
print(word)
find_words(st)

Python GCSE - Using Lists

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.

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