user4444
user4444

Reputation: 45

if a lowercase element is in the list without changing the list to lowercase

I am trying to create a program that replaces any word entered in the input by the word that goes along with it in the dictionary. Here is the dictionary:

slang = {'phone': 'dog and bone', 'queen': 'baked bean', 'suit': 'whistle and flute', 'money': 'bees and honey', 'dead': 'brown bread', 'mate': 'china plate', 'shoes': 'dinky doos', 'telly': 'custard and jelly', 'boots': 'daisy roots',  'road': 'frog and toad', 'head': 'loaf of bread', 'soup': 'loop the loop', 'walk': 'ball and chalk', 'fork': 'roast pork', 'goal': 'sausage roll', 'stairs': 'apples and pears', 'face': 'boat race'} 

And here is an example of the output this would make.

Sentence: I called the Queen on the phone
I called the baked bean on the dog and bone

I have tried to code this program, and I have gotten it to print out the output (nearly). I just don't know how to ask if the inputted words are inside the dictionary without replacing the word that is capitalised with a lowercased version.

Here's an example of my output:

Sentence: I called the Queen on the phone
i called the baked bean on the dog and bone

This is the code I have tried and I realise that this issue is arising because I am setting the sentence as lower at the beginning. I have tried to set the 'word' to lower before going into the for loop but this doesn't work either because 'word' is unknown until the for loop.

slang = {'phone': 'dog and bone', 'queen': 'baked bean', 'suit': 'whistle and flute', 'money': 'bees and honey', 'dead': 'brown bread', 'mate': 'china plate', 'shoes': 'dinky doos', 'telly': 'custard and jelly', 'boots': 'daisy roots',  'road': 'frog and toad', 'head': 'loaf of bread', 'soup': 'loop the loop', 'walk': 'ball and chalk', 'fork': 'roast pork', 'goal': 'sausage roll', 'stairs': 'apples and pears', 'face': 'boat race'}
new_sentence = []
sentence = input("Sentence: ").lower()
words_list = sentence.split()
for word in words_list:
  if word in slang:
    replace = slang[word]
    new_sentence.append(replace.lower())
  if word not in slang:
    new_sentence.append(word)
separator = " "
print(separator.join(new_sentence))

Thank you so much!

Upvotes: 0

Views: 64

Answers (2)

balderman
balderman

Reputation: 23815

Something like the below:

slang = {'phone': 'dog and bone', 'queen': 'baked bean'}

def replace_with_slang(sentence):
  words = sentence.split(' ')
  temp = []
  for word in words:
    temp.append(slang.get(word,word))
  return ' '.join(temp)


print(replace_with_slang('I called the phone  It was the queen '))

Upvotes: 1

sushanth
sushanth

Reputation: 8302

You can use list comprehension instead,

slang = {'phone': 'dog and bone', 'queen': 'baked bean', ...}

Sentence = "I called the baked bean on the dog and bone"
print(" ".join(slang.get(x.lower(), x) for x in Sentence.split()))

I called the baked bean on the dog and bone

Upvotes: 1

Related Questions