如何用python制作语言词典?

我希望用户能够插入英语单词并返回西班牙语。这就是我所拥有的:

选择 | 换行 | 行号
  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" 
# 回答1

请至少在发布前测试您的代码。"while True"是无限的,因为此行永远不会测试为True

选择 | 换行 | 行号
  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"):

要在列表中查找内容,可以使用指数

选择 | 换行 | 行号
  1. el_number = english.index(word)
# 回答2

为什么不使用内置的字典结构呢?大致如下:

选择 | 换行 | 行号
  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.  

标签: python

添加新评论