我有一个包含两列的文件:
one uno
two dos
three tres
hello hola
我想把这个文件读入字典,打印出用户输入的英语单词的西班牙语翻译。如果英文单词不存在,则应打印“not there”语句。我有一些代码,但当我运行它总是打印出“不在那里”,无论我输入什么。我能做些什么来解决这个问题?谢谢
def spanish(word):
newDict = {}
spanishfile = open("eng2sp.txt","r")
for line in spanishfile:
(word, val) = line.split()
newDict[str(word)] = val
if 'word' in newDict:
print(newDict['word'])
else:
print("Not there")
def main():
word = str(input("Please enter the English word you would like to translate or enter EXIT to quit: "))
while word != "EXIT":
spanish(word)
word = str(input("Please enter the English word you would like to translate or enter EXIT to quit: "))
main()
两大问题:
检查包含“word”(可能不是)的文本字符串是否在dict中。将其更改为:
if word in newDict: print newDict[word]
覆盖传递到函数中的任何
word
,使其等于文件中的每个英文单词。将其更改为eng,spa = line.split()
或其他形式,以不覆盖传递到函数中的参数在
spanish()
函数中,使用相同的名称命名参数和局部变量,然后不检查参数与newDict
的对应关系,而是检查字符串word
,这就很好地解释了为什么总是得到"Not there"
,而且您不需要newDict[str(word)] = val
,因为您已经将其读取为string
这是您的解决方案:
相关问题 更多 >
编程相关推荐