As you will understand from my question, I am new to programming and as most people who are new to this, I am having issues comprehending some of the code. I came across the following code in Python which translates some words from German to English and returns a string of the translation:
deu2eng = {
'ich':'I',
'gehe':'go',
'nach':'to',
'die':'the',
'kirche':'church'}
def trans(eng2deu):
translation = ''
for word in eng2deu.split():
if word in deu2eng:
translation+= deu2eng[word] + ' '
else:
translation += word + ' '
return translation
When I run the following it works:
trans('ich gehe nach die kirche')
However there are some issues. I can't get to understand how I can get it to be case insensitive (e.g. if I type Kirche instead of kirche, it will return Kirche instead of church). I tried using the lower() method to no avail. But most importantly, I do not understand the following line and why it works:
translation+= deu2eng[word] + ' '
From what you can infer, this is quite basic, but I would like to fully comprehend what is happening with this code as I am stuck in the 2 aforementioned things.
To make it case-insensitive, change the for line to:
for word in lower(eng2deu).split()
Here's the step-by-step explanation of translation+= deu2eng[word] + ' ':
word from the deu2eng dictionary.translation to the concatenation of translation and that string.Remember that x += y is just short for x = x + y. So
translation+= deu2eng[word] + ' '
means
translation = translation + deu2eng[word] + ' '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With