Thursday, December 24, 2009

Why does this Python coding not work?

hi i'm trying to create a program to take a phrase convert it into german, and then convert it back into english using to different dictionaries and text files. The first part works, it splits the string and converts it to german, but it doesn't convert back to english again. It just returns ';hund'; (dog in german). Please help!





def translate_to_ger(phrase):


phrase.lower()


phrase = phrase.split()


for item in phrase:


translated_eng = eng_to_ger[item]


print translated_eng


return translated_eng





def translate_to_eng(translated_eng):


for item in translated_eng:


translated_ger = ger_to_eng[translated_eng]


print translated_ger


return translated_ger





eng_to_ger = {}


for line in open(';english2german.txt';, ';r';):


(english, german) = line.split()


eng_to_ger[english] = german





ger_to_eng = {}


for line in open(';german2english.txt';, ';r';):


(german, english) = line.split()


ger_to_eng[german] = englishWhy does this Python coding not work?
In the translate_to_eng() function you need to break the passed-in argument string into an array of words by using split() as you did in translate_to_ger(). (To see why, compare the result of 'for item in ';xyz';: print item' against the result of 'for item in ';xyz';.split(): print item'.)





And then you need to use 'item' as the key into the ger_to_eng dictionary. Right now you're using the entire argument 'translated_eng' as the key.





You might also want to force the passed-in string to lower case, especially given that German uses capitals on nouns -- so really the German word for ';dog'; is ';Hund';, not ';hund';. The right answer here really depends on what your word lists look like.





After you have this working for single-word phrases you're going to need to make changes to get it working for multi-word phrases. You need to accumulate multiple words into the answer, so you'll want add each translated word to a list and finally return the result of a join() on that list.Why does this Python coding not work?
Hi,





Just an observation here, but the word ';hund'; is a word you'll find in the English Dictionary. It refers to Hundred or Hundreds.





Perhaps that is why you program appears not to work.





Regards,





TgTips

No comments:

Post a Comment