By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,199 Members | 1,077 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,199 IT Pros & Developers. It's quick & easy.

How to make a language dictionary in python?

P: 2
I want the user to be able to insert a word in english and have it returned in spanish.
This is what I have:
Expand|Select|Wrap|Line Numbers
  1. # Two arrays, one for english words, the other for their spanish hit.
  2. english = [ ]
  3. spanish = [ ]
  4.  
  5. # 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.
  6.  
  7. file=open("eng-span.txt", "r")
  8.  
  9. while True :
  10. # Read one line
  11.  
  12.     line = file.readline()
  13.  
  14.     # Check, if it's the last line
  15.  
  16.     if line == "" :
  17.         break
  18.  
  19.     word_pair = line.split ("\t")
  20.     english.append (word_pair[0])
  21.     spanish.append (word_pair[1])
  22.  
  23. print " Enter the English word for which you want the Spanish definition to: "
  24. word = raw_input()
  25.  
  26. # 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...
  27.  
  28. for i in english:
  29.     if word in english :
  30.         print spanish[ i ]
  31.     else :
  32.         print "No definition" 
Oct 21 '10 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 624
Please at least test your code before posting. The "while True" is infinite because this line will never test as True
Expand|Select|Wrap|Line Numbers
  1.     # Check, if it's the last line
  2.     if line == "" :     ## still contains newline so is "\n"
  3.         break 
  4. #
  5. #     instead, use this
  6. for rec in open("eng-span.txt", "r"):
To find something in a list, you can use index
Expand|Select|Wrap|Line Numbers
  1. el_number = english.index(word)
Oct 21 '10 #2

Expert 100+
P: 391
Why not use the built in dictionary structure for this?

Something like this:
Expand|Select|Wrap|Line Numbers
  1. d=dict()
  2. #create language dictionary
  3. for line in open('eng-span.txt'):
  4.     temp=line.split('\t')
  5.     d[temp[0]]=temp[1].strip()
  6.  
  7. e=raw_input("Enter english word for translation: ")
  8. try:
  9.     print "Spanish is: ", d[e]
  10. except:
  11.     Print "No translation found"
  12.  
Oct 25 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.