eskoka
eskoka

Reputation: 97

Translate a phrase using dictionary? (python)

I have to do a rough translation of the phrase into English using my dictionary, but I'm not sure how.

c1 = "befreit"
c2 = "baeche"
c3 = "eise"
c4 = "sind"
c5 = "strom"
c6 = "und"
c7 = "vom"

mydict = {c1:"liberated", c2:"brooks", c3:"ice", c4:"are", c5:"river", c6:"and", c7:"from"}

print(mydict.keys())
print(mydict.values())

phrase = "vom eise befreit sind strom und baeche"
print(phrase)

phrase.split()
for x in phrase:
    #something goes here

Upvotes: 1

Views: 3957

Answers (3)

YS-L
YS-L

Reputation: 14738

You can use the dict to map each word in the original phrase to the desired language, whenever possible:

c1 = "befreit"
c2 = "baeche"
c3 = "eise"
c4 = "sind"
c5 = "strom"
c6 = "und"
c7 = "vom"

mydict = {c1:"liberated", c2:"brooks", c3:"ice", c4:"are", c5:"river", c6:"and", c7:"from"}

phrase = "vom eise befreit sind strom und baeche"
translated = " ".join([mydict.get(p, p) for p in phrase.split(' ')])
print translated
# from ice liberated are river and brooks

Note that you might need to have a more careful tokenization scheme instead of using split(), to handle cases such as words followed by punctuation.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

store both in your dict as keys an values:

 mydict = {"befreit":"liberated", "baeche":"brooks", "eise":"ice", "sind":"are", "strom":"river", "und":"and", "vom":"from"}


phrase = "vom eise befreit sind strom und baeche"
print(" ".join([mydict[w] for w in phrase.split()]))
from ice liberated are river and brooks

Upvotes: 1

Dyrborg
Dyrborg

Reputation: 877

You are almost there:

c1 = "befreit"
c2 = "baeche"
c3 = "eise"
c4 = "sind"
c5 = "strom"
c6 = "und"
c7 = "vom"

mydict = {c1:"liberated", c2:"brooks", c3:"ice", c4:"are", c5:"river", c6:"and", c7:"from"}

print(mydict.keys())
print(mydict.values())

phrase = "vom eise befreit sind strom und baeche"
print(phrase)

translated_string = " ".join([mydict.get(e, "") for e in phrase.split(" ")])
print translated_string

Dictionaries, looking at the syntax, work very similar to lists: By typing

element = mylist[0]

you ask the list "give me the element at index 0". for dictionaries you can do something similar:

value = mydict["key"]

However if the key is not in the dictionary you will get a keyerror and your program will crash. An alternative method is to use get():

value = mydict.get("key","")

This will return the value of the key if it exist, and if it doesn't, return whatever you stated in the second argument (here an empty string). Keys for dictionaries can be whatever immutable object you want it to be. In your case a String.

Upvotes: 0

Related Questions