问题
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
回答1:
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
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/26791711/translate-a-phrase-using-dictionary-python