Searching for key words in python - 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.

Related

How to split a paragraph into sentences when they contain words such as "U.S." and "Inc."

I'm writing a celebrity trivia quiz in python that takes clues from Wikipedia.
I'm using the following code to split the paragraphs into sentences:
sentences = line.split(". ")
It works for everything except when there's a word that ends in a period in the sentence. For example, "XXX is a U.S. senator." gets incorrectly split into "XXX is a U.S."
I've created a list of exceptions where I remove the period from such words:
line = line.replace("Dr. ", "Dr ").replace("Mr. ", "Mr ").replace("Gen. ", "Gen ").replace("No. ", "No ").replace("U.S. ", "US ")
But for anything not in the list (e.g. "U.K." or "Inc."), the sentence gets stopped at the word ending in a period.
I'm not sure how else I can approach this. How can I preserve these words while still splitting into sentences?
This might work:
paragraphs = full_content.split("\n\n")
Where full_content is the data you want to split into paragraphs.
You can use list of abbreviations with dot.
You should add this list into a file and check that if . belong a word at the file, skip it

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 check if any word of string match another string

I'm trying to find some function in Python which can help me with finding some word-matches of two different strings.
For example we have 2 strings:
"I am playing basketball everyday"
"basketball is the worst game ever"
And I want this function to return true if "basketball" was found in both strings.
You can find which are the common words in two phrases:
common_words = set(phrase1.split()).intersection(phrase2.split())
You can check if a word is in both phrases by simply checking if it is in the common_words set (example: if word in common_words: ...).
You can also check how many elements this set has. If len(common_words) == 0 then phrase1 and phrase2 contain no common words.
l = ["I am playing basketball everyday", "basketball is the worst game ever"]
for x in l:
print (x)
if "basketball" in x.lower():
print (True)
str1 = "I am playing basketball everyday"
str2 = "basketball is the worst game ever"
if "basketball" in str1 and "basketball" in str2:
print "basketball is in both strings!"
See: Python - Check If Word Is In A String

Fail to find multi-strings

about_pet = input("A sentence about your pet")
multi = "dog", "cat"
if all(multi) in about_pet:
print ("wow, you have one more pets!", " Thanking you reading my
story:) ")
elif "dog" in about_pet:
print ("Ah, a dog.", " Thanking you reading my story:) ")
elif "cat" in about_pet:
print ("Oh, a cat.", " Thanking you reading my story:) ")
i don't know how to search two strings in an input. The above captured is what I had done.
All works on an iterable, it returns true if all items within the iterable are true.
multi = ["dog", "cat"]
if all(m in about_pet for m in multi):
print ("wow, you have one more pets!", " Thanking you reading my story:) ")
you could put an if statement within an if statement so it checks if the sentence contains the word cat first then if it does it goes on check if it also contains the word dog to see if both words are in the string.
about_pet = raw_input("A sentence about your pet")
if "cat" in about_pet:
if "dog"in about_pet:
print "wow, you have one more pets! Thanking you reading my story:) "
elif "dog" in about_pet:
print "Ah, a dog. Thanking you reading my story:) "
elif "cat" in about_pet:
print "Oh, a cat. Thanking you reading my story:) "
I know this might not be the cleverest solution but it is quite easy to understand.
To simplify it you can check them one after another using an and
if "cat" in about_pet and "dog" in about_pet:
or:
if "cat" and "dog" in about_pet:
If you are using Python 2.7.10 ,you also need to use raw_input instead of input as in Python 2.7.10 input only accepts integers and float. And if you're using python 2.7.10(as i am) i don't do my print in brackets as it prints out the brackets sometimes. Also i have a suggestion to add code for when the user says they don't have a pet using an else at the end. Plus you don't have to put sentences in separate speech marks. I hope this helped!

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.

Categories