1. 程式人生 > >python 學習 字典可加多重解釋 DAY24

python 學習 字典可加多重解釋 DAY24

def rdic():
    fr = open('dic.txt','r')    
    for line in fr:
        line = line.replace("\n",'')
 #       print(line)
        v = line.split(':')
 #       print(v)
        dic.setdefault(v[0],[]).append(v[1])
        keys.append(v[0])
    fr.close()
 
def centre():
    n = input("請輸入進入相應模組(新增、查詢、退出):")
    if n =="新增":
        key = input("請輸入英文單詞:")
        
        if key not in keys:
            value = input("請輸入中文單詞:")
            dic[key] = value
            keys.append(key)
            print("單詞已經新增成功")
        else:
            value = input("請輸入中文單詞:")
            dic.setdefault(key,[]).append(value)
            print("該單詞已經新增至字典庫")
    elif n =="查詢":
        key = input("請輸入英文單詞:")
        if key in keys:
            print("中文意思為:"+",".join(dic[key]))
        else:
            print("字典中未找到這個單詞")
    elif n =="退出":        
        return 1
    else:        
        print("輸入有誤")
        return 0
    
def wdic():#寫入檔案程式碼 通過keys的順序寫入
    fw = open('dic.txt','w')
    for k in keys:
        fw.write(k+':'+",".join(dic[k])+'\n') 
    fw.close()
 
if __name__=="__main__":
    keys = [] #用來儲存讀取的順序
    dic = {}
    while True:
        rdic()
        n = centre()
        wdic()
        if n == 0:
            continue
        elif n == 1:
            break