Jay
Jay

Reputation: 45

Simple language translator

So my friends and I are making a few languages for fun and I decided this would be a good chance to practice python and make a translator. The language is very simple, so at this point I was thinking okay I can make separate dictionaries to house all of the different parts of speech, then tie them together into a string. Initially I started with a pronoun dict and and a verb dict to start just to get the translating part down. This is what I have now, though it doesn't work

pro = {"I":"ii"}
verb = {"am":"esti"}
noun = {"theatre":"trieto"}
adj = {"red":"reada"}

sentence = input("translate: \n")
for word in sentence.split(" "):
    print(pro.get(word, word)+ verb.get(word, word))

I want to make a translator that is mainly plugging in words to the particular part of speech in the string.

If there is a completely different way of doing this that would make it easier I'm all ears. Also I am having a hard time learning nltk for this as well, so if you know how to use nltk for this then I would be very appreciative to learn how.

Upvotes: 1

Views: 300

Answers (2)

Tim Johns
Tim Johns

Reputation: 540

To start, you can just check if the word appears in each dictionary, and print the translation, if it does.

pro = {"I":"ii"}
verb = {"am":"esti"}
noun = {"theatre":"trieto"}
adj = {"red":"reada"}

sentence = input("translate: \n")
for word in sentence.split(" "):
    if word in pro:
        print(pro[word] + " ")
    elif word in verb:
        print(verb[word] + " ")
    elif word in noun:
        print(noun[word] + " ")
    elif word in adj:
        print(adj[word] + " ")
    else:
        print(word + " ")

Upvotes: 0

abarnert
abarnert

Reputation: 365637

If you want to treat each word as potentially any part of speech, you don't have any need for separate dictionaries for each part of speech, just one big dictionary.

So, let's merge them:

translate = {}
for d in pro, verb, noun, adj:
    translate.update(d)

… and now, what you want to do is trivial:

for word in sentence.split(" "):
    print(translate.get(word, word))

If, on the other hand, you have some logic to pick a part of speech based on, say, position, you need to write that logic.

For example, maybe the first word is always a pronoun, then a verb, then 0 or more adjectives, then a noun. (That's a pretty silly grammar for English, but it's an example to get started.) So:

p, v, *aa, n = sentence.split()
print(pro.get(p, p))
print(verb.get(v, v))
for a in aa:
    print(adj.get(a, a))
print(noun.get(n, n))

Upvotes: 2

Related Questions