0

Sorry if the title was confusing. The exercise I'm working on is to write a function which takes two arguments: a dictionary which maps Swedish words to English, and a string corresponding to a Swedish sentence. The function should return a translation of the sentence into English

My function works well regarding the translation, but the output it produces is in the wrong order.

For example, the following argument, consisting of a dictionary and a string in Swedish (Eng: "A fine monkey")

translate_sentence({'en': 'a', 'fin': 'fine', 'apa': 'monkey'}, 'en fin apa')  

should return

'a fine monkey'

but instead it returns

'a monkey fine'

Here is the script for the function:


def translate_sentence(d, sentence): 
    result = []                     
    delimiter = ' '                 
    s = sentence.split()            
    for word in d:                        
        if word in sentence and word in d:
            d_word = (d[word])
            result.append(d_word)
    for word in s:                          
        if word in s and word not in d:
            s_word = word
            result.append(s_word)
    return delimiter.join(result)    

As I said before, the problem is that the function returns the translated string with the words in the wrong order. I know that python dictionaries aren't ordered, isn't there some way to get the output to be in the same order as sentence?

Hantan G
  • 7
  • 3
  • As a side note, dicts in Python 3.6+ are ordered https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744 – Lesiak Apr 24 '19 at 18:05

2 Answers2

1

This one-liner seems to work fine. Lookup each word in the dictionary and join in the same order as the input sentence.

def translate_sentence(d, sentence): 
    return ' '.join(d.get(word, word) for word in sentence.split())

Example:

>>> translate_sentence({'en': 'a', 'fin': 'fine', 'apa': 'monkey'}, 'en fin apa')  
'a fine monkey'
>>> 
rdas
  • 20,604
  • 6
  • 33
  • 46
1

We check the value for each key, where key is a word in the string, and if we don’t find it, we use the original word

def translate_sent(d, s): 
    return ' '.join(d[word] if word in d else word for word in s.split())

>>> translate_sent({'en': 'a', 'fin': 'fine', 'apa': 'monkey'},        'en fin apa')  
'a fine monkey'
>>> translate_sent({'en': 'a', 'fin': 'fine'}, 'en fin apa')  
‘a fine apa’
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40