Python dictionary

Asked

Viewed 1,281 times

2

Next, I have a table with words in a language, I will use example to suppose, from Portuguese to English. These words are in a dictionary where the key is the Portuguese word and the value is the English word. Using the dictionary keys in a string, forming a sentence, how would it be translated into English? Or is it how I inject a sentence and return its value to me? *Let’s consider that it would be a sentence and not just a word... I’m trying to move to a reading list.

  • I won’t be able to sleep, someone please help

3 answers

5


From what I understand I think you can do the following:

d = {'olá': 'hello', 'como':'how', 'estás':'are', 'tu':'you'}
frase = 'olá como estás tu' # aqui seria o teu input('frase')
words = frase.split() # dividir por espaços para obter uma lista com as palavras
print(' '.join(d[w] for w in words)) # hello how are you

DEMONSTRATION

A better prepared version with the ability to circumvent possible key errors (Keyerror):

d = {'olá': 'hello', 'como':'how', 'estás':'are', 'tu':'you'}
frase = 'olá como estás tu aí em cima' # aqui seria o teu input('frase')
words = frase.split() # dividir por espaços para obter uma lista com as palavras
print(' '.join(d[w] if w in d else w for w in words)) # hello how are you aí em cima

DEMONSTRATION

In this last version if the word in Portuguese does not exist in the dictionary simply does not translate it.

From comments I realized that maybe you want whole sentences as keys, that’s even less work:

d = {'olá como estás?':'Hello how you', 'grande almoço': 'nice lunch'}
hey = 'olá como estás?'
print(d[hey]) # Hello how you
hey = 'grande almoço'
print(d[hey]) # nice lunch
hey = 'hey hey hey'
if hey not in d: # não exiSta no dic
  print(hey) # hey hey hey

DEMONSTRATION

  • explains something, I’m new at Python, you are doing the opposite, type ~> key value ?

  • Hello @Wéllingthonm.Souza , no, the boy who asked the question says "... where the key is the English word ", that is to say, {chave1: valor1, chave2: valor2}

  • Yes, I understand, more to translate from Inglês to the Português

  • No @Wéllingthonm.Souza, what is said in the question is "These words are in a dictionary where the key is the Portuguese word and the value is the English word...as it would be translated into English? "

  • Thank you, but you thought a compound word like "excuse me" would just be translated into a word?

  • @Amador.py ,you should know in advance if it is to translate by word or phrase (e.g., split by point). Doing something like the one I think you want right now is not trivial and requires a lot of study

  • Can you explain the last line?! the function of 'Join' and why’d[w]'

  • @Amador.py, of course, but there’s nothing better than seeing. That join() of the last example is equivalent to this: https://repl.it/MIjC/1

  • By phrase @Wéllingthonm.Souza, it happens to have some compound words that translate to one word only. Thanks for the indication

  • @Amador.py this is even easier, you can do this: https://repl.it/MIRj/3

  • I understood more than half the code, I just didn’t understand the d in the index w (d[w]), that when w is already contained in d (w in d, was that Else). @Wéllingthonm.Thank you

  • @Amador.py d[x] stores the value in d whose key is x

  • Aren’t you going to define the words / phrases ? See: repl it.

  • 1

    Yes, all right. Thank you for sharing knowledge.

  • @Amador.py, we’re here for that. You’re welcome

Show 10 more comments

0

You can do it like this:

dicionario = {
  'good morning': 'bom dia',
  'good night': 'boa noite',
  'Hello': 'Ola',
  'good': 'bom',
  'day': 'dia',
  'this': 'isso',
  'will': 'vai',
  'translate': 'traduzir',
  'word': 'palavra',
  'for': 'por'
}

def traduz(frase, dicionario):
    saida = []
    # Verifica se o dicionario contem a frase
    if dicionario.get(frase):
      traducao = dicionario.get(frase)
      saida.append(traducao if traducao else frase)
    else: # Caso nao tem, divida a frase em uma lista de palavras
      frase = frase.split()
      # Iterar as palavras de entrada e acrescentar tradução
      for palavra in frase:
          traducao = dicionario.get(palavra)
          saida.append(traducao if traducao else palavra)

      # Retorna saida
    return ' '.join(saida)

To use, call the method

# Traduz a frase informada pelo usuario.
print(traduz(input('Digite uma frase: '), dicionario))
# Traduz a frase pre-definida.
print(traduz('good night', dicionario))
# Traduz palavra por palavra
print(traduz('isso vai traduzir palavra por palavra', dicionario))

That response was based on this reply in the Soen.

See working on repl it.

  • The dictionary has the keys/changed, the AP says the keys are in en

  • He assumed it was Português ~> Inglês

  • Exactly. Key in Portuguese and value in English. See in the question: "[...] where the key is the Portuguese word and the value is the English word"

  • Thank you, but you thought a compound word like "excuse me" would just be translated into a word?

0

A little late, I would like to add the functionality to search for ready expressions like 'good morning'->'good Morning' differentiating 'Good trip'->'good trip', ie to go beyond word-for-word translation.

Basically we have this dictionary:

dicionario = {
        'bom':'good',
        'boa':'good',
        'dia':'day',
        'bom dia':'good morning',
        'acordou':'wake up',
        'viagem':'trip',
        'filme':'movie',
        'apertem os cintos... o piloto sumiu':'Airplane',
        'assisti':'watched',
        'eu':'I',
        'nunca':'never',
        'o':'the'
}

Notice it’s even named after a movie.

First we make a function that checks whether a sequence or word is in the dictionary:

def existe_traducao(dicionario, lista):
    sequencia = ' '.join(x.lower() for x in lista)
    if sequencia in dicionario:
        return dicionario[sequencia]
    return ''

>>> print(existe_traducao(dicionario, ['Boa']))
good
>>> print(existe_traducao(dicionario, ['boa', 'viagem']))

>>> print(existe_traducao(dicionario, ['bom', 'dia']))
good morning

Now we just need to translate the phrase by looking for expressions. For this, we go from the current word to the end, after the current word to the end -1 and so on looking for a key in the dictionary:

def traduz(dicionario, frase):
    palavras = frase.split()
    lista_traduzida = []
    i = 0
    while i < len(palavras):
        for j in range(len(palavras), i, -1):
            traducao = existe_traducao(dicionario, palavras[i:j])
            if traducao != '': #Se achei tradução
                lista_traduzida.append(traducao)
                i = j
                break
        else:
            lista_traduzida.append(palavras[i].lower())
            i+=1
    return ' '.join(lista_traduzida)

>>> frase = 'Bom dia AlexCiuffa' #AlexCiuffa não está no dicionário
>>> print(traduz(dicionario, frase))
good morning AlexCiuffa
>>> frase = 'Boa viagem amigo' #amigo não está no dicionário
>>> print(traduz(dicionario, frase))
good trip amigo
>>> frase = 'Eu nunca assisti o filme Apertem os cintos... O piloto sumiu'
>>> print(traduz(dicionario, frase)) #perceba que a frase possui um titulo de filme
I never watched the movie Airplane

Browser other questions tagged

You are not signed in. Login or sign up in order to post.