我試圖說明翻譯字典即:如何使一個字典,對於關鍵是單詞在英語和值希臘字(UTF-8),我得到一個KeyError,當我嘗試獲得值
當一個英文單詞給出我回到含義希臘(UTF-8)
#Possible Content Of File: #"Hello,Γεια\n" #"Car,Αμαξι\n" with codecs.open("dict.txt",'r',encoding='utf8') as f: lines= f.read() #contains all the lines of the file word=raw_input("Word To Find\n") flag=0 temp="" temp2="" dictionary={} #here is an algorithm i came up with, to seperate the string and get on temp the key #and on temp2 the value , then i add them on the dictionary for i in range(0,len(lines)): if flag==0: temp+=lines[i] if lines[i]==',': flag=1 continue if lines[i]=='\n': flag=0 dictionary.update({temp:temp2}) #adding the key and the value #(the value is in utf-8) temp="" temp2="" if flag==1: temp2+=lines[i] #print(dictionary.keys()) # [u'Hello,',u'Car,'] #print(dictionary.get(word)) returns None print(dictionary[word])# KeyError
Note: The file contains this kind of strings: "Hello,Γεια\n" and "Car,Αμαξι\n"
Error: print(dictionary[word]) throws a KeyError
This is Python 2.7
感謝很多提前
調試步驟1:'print(dictionary.keys())'。調試完成。修復代碼的步驟1:'dic_file = open('dict.txt'); dictionary = {e:g.strip()for e,g in(line.split(',')for line in dic_file)}'。 –
我收到相同的內容11次,如果我打印字典 – Phill