How to make a language dictionary in python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hoolaboola
    New Member
    • Oct 2010
    • 2

    How to make a language dictionary in python?

    I want the user to be able to insert a word in english and have it returned in spanish.
    This is what I have:
    Code:
    # Two arrays, one for english words, the other for their spanish hit.
    english = [ ]
    spanish = [ ]
    
    # The words and definitions are in a file. English word first then tab and then Spanish definition on one line. Then add the words in their respective arrays.
    
    file=open("eng-span.txt", "r")
    
    while True :
    # Read one line
    
        line = file.readline()
    
        # Check, if it's the last line
    
        if line == "" :
            break
    
        word_pair = line.split ("\t")
        english.append (word_pair[0])
        spanish.append (word_pair[1])
    
    print " Enter the English word for which you want the Spanish definition to: "
    word = raw_input()
    
    # Tricky part for me: a for-cycle that checks whether the inserted word exists in the array 'english' and then prints the corresponding Spanish definition from array 'spanish'. I have the cycle all wrong...
    
    for i in english:
        if word in english :
            print spanish[ i ]
        else :
            print "No definition"
    Last edited by hoolaboola; Oct 21 '10, 06:32 PM. Reason: grammar
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Please at least test your code before posting. The "while True" is infinite because this line will never test as True
    Code:
        # Check, if it's the last line
        if line == "" :     ## still contains newline so is "\n"
            break 
    #
    #     instead, use this
    for rec in open("eng-span.txt", "r"):
    To find something in a list, you can use index
    Code:
    el_number = english.index(word)

    Comment

    • Glenton
      Recognized Expert Contributor
      • Nov 2008
      • 391

      #3
      Why not use the built in dictionary structure for this?

      Something like this:
      Code:
      d=dict()
      #create language dictionary
      for line in open('eng-span.txt'):
          temp=line.split('\t')
          d[temp[0]]=temp[1].strip()
      
      e=raw_input("Enter english word for translation: ")
      try:
          print "Spanish is: ", d[e]
      except:
          Print "No translation found"

      Comment

      Working...