2

I'm trying to create a program that takes an input and then converts it from an Australian Aboriginal language into English. While the rest of the program is functional, the output is printed in the wrong format. The output that I'm receiving is:

ngaju
kuja-piya
malilyi

What I want to receive is: ngaju kuja-piya malilyi

Here is my full code:

dictionary = open('dictionary.txt')
words = {}
for line in dictionary:
  english, aboriginal = line.split(',')
  words[english] = aboriginal
translator = input("English: ")
while translator:
  sentence = translator.split()
  for word in sentence:
    print(words[word], end='')
  translator = input("English: ")

And here are the contents of dictionary.txt:

afternoon,wuraji-wuraji
I,ngaju
bird,jirripirdi
like,kuja-piya
dance,juka-pinyi
python,malilyi
laugh,ngarlarrimi
we,ngalipa
  • 2
    When you iterate over the file with `for line in dictionary:` the value `line` has an ending newline character. You might want to do `english, aboriginal = line.strip().split(',')` to get rid of it. – Matthias Apr 04 '20 at 09:07
  • May I know what did you prefer an answer that does not explain the problem rather that the one explaining it ? – azro Apr 05 '20 at 08:13

2 Answers2

3

I'd say it's the new-line char from the file, you keep in in aboriginal variable which will for example values ngaju\n so when you print it, the \n makes a new line, add a rstrip() operation to remove leading space/new-line char

for line in dictionary:
    english, aboriginal = line.rstrip().split(',')
    words[english] = aboriginal

The safest way, apply .strip() on both word to be sure you take only what needed, but a little overkill if your file is well formatted (no space)

for line in dictionary:
    english, aboriginal = line.split(',')
    words[english.strip()] = aboriginal.strip()
codeforester
  • 39,467
  • 16
  • 112
  • 140
azro
  • 53,056
  • 7
  • 34
  • 70
2

I added strip() to remove trailing spaces for each word like this:

dictionary = open('dictionary.txt')
words = {}
for line in dictionary:
    english, aboriginal = line.split(',')
    words[english] = aboriginal.strip()

translator = input("English: ")
while translator:
    sentence = translator.split()

    print(' '.join(words[word] for word in sentence))
    translator = input("English: ")

INPUT

I like python

OUTPUT

ngaju kuja-piya malilyi

Anatol
  • 3,720
  • 2
  • 20
  • 40