Firebase 版电子词典
学英语是许多 人一辈子的麻烦 。 所以本例中,我们开发一个英汉词典,用户执
行程序后,单击“翻译”按钮即可显示该单词的中文翻译 。
英汉词典标准版
因为这个案例的数据必须要存储在 Firebase 数据库中,所以我们先通过以下程
序来完成单词数据的导入。
数据导入
这个案例中将使用 csv 文件作为数据来源, csv 是一种通用而简单的数据格
式,我们首先利用程序把 eword.csv 文件中的英文单词全部保存至 Fire base 数据库的
English 节点中 。

 

 

 

from firebase import firebase

url = 'https://chiouapp01-74bde.firebaseio.com/English'
fb = firebase.FirebaseApplication(url, None)
datas=fb.get(url, None)

def CkeckKey(no):
    key_id=""
    if datas != None:
        for key in datas:
            if no==datas[key]["eword"]: # 读取键名
                key_id = key 
                break
    return key_id
        
### 主程序从这里开始 ###

with open('eword.csv','r', encoding = 'gbk') as f:
    for line in f:
        eword,cword = line.rstrip('\n').split(',')
        word={'eword':eword,'cword':cword}
        if CkeckKey(eword) == "":      # 判断键是否存在
            fb.post(url, word)  
            print(word)
    print("\n转换完毕!")         

 

 

 

 

 

 

 

 

 

 

 

 

 

自定义一个函数 menu , 用于实现主菜单显示。
def menu():
    os.system("cls")
    print("英 汉 词 典")
    print("-------------------------")
    print("1. 翻  译  单词")
    print("2. 新  增  单词")
    print("3. 显  示  单词")
    print("4. 修  改  单词")
    print("5. 删  除  单词")
    print("0. 结  束  程  序")
    print("-------------------------")
 自 定 义函数 CkeckKey ,实现根据 no 找到该条数据的 id ,注意参数
no 为字符串 类型 。
def CkeckKey(no):
    key_id=""
    if datas != None:
        for key in datas:
            if no==datas[key]["eword"]: # 读取键名称
                key_id = key 
                break
    return key_id 
自定义函数 input_data ,可连续新增数据,按 Ente r 键后才会停止输
入并返回主菜单。
def input_data(): 
    global datas       
    while True:
        eword =input("请输入英文单词(Enter==>停止输入)")
        if eword=="": 
            break
        key_id = CkeckKey(eword)   
        if key_id != "":      # 判断键是否存在
            print("{} 单词已存在!".format(datas[key_id]))
            continue
        cword=input("请输入中文翻译:")
        word={'eword':eword,'cword':cword}
        key_id=fb.post(url, word)["name"]
        time.sleep(2)
        if datas == None: 
            datas = dict()
        datas[key_id]=word
        print("{}已被储存完毕".format(word))
数据输入成
功后会返回 一 个 diet 对象,并自动产生唯 一 编 号 ,通过 key_id=tb.
post(url, wo时)[”name”] 可以从 name 键中取得这个编号。
自 定义函数 disp_data , 实现以每页 15 条数据的分页显示效果 。
def disp_data():
    global datas
    datas=fb.get(url, None)
    if datas != None:
        n,page=0,15
        for key in datas:
            if n % page ==0:
                print("单词\t中文翻译")
                print("======================")
            print("{}\t{}".format(datas[key]["eword"],datas[key]["cword"]))
            n+=1
            if n == page:
                c=input("请按 Enter 显示下一页,Q 键返回主菜单") 
                if c.upper() == "Q":return
                n=0
        c=input("请按任意键返回主菜单")
自定义函数 search_data , 用于查询英文单词 。
def search_data():
    while True:
        eword =input("请输入要查询的英文单词(Enter==>停止输入)")
        if eword=="": break
        key_id = CkeckKey(eword)
        if key_id != "":      # 判断键是否存在
            print("中文翻译:{}".format(datas[key_id]["cword"]))
        else:
            print("{} 单词不存在!\n".format(eword))  
        input("请按任意键继续翻译…") 
自定义函数 edit data ,用于修改英文单词。
def edit_data():
    while True:
        eword =input("请输入要修改的英文单词(Enter==>停止输入)")
        if eword=="": 
            break
        key_id = CkeckKey(eword)
        if key_id != "":      # 判断键是否存在
            print("原来中文翻译:{}".format(datas[key_id]["cword"]))  
            cword=input("请输入中文翻译:")
            word={'eword':eword,'cword':cword}
            datas[key_id]=word 
            fb.put(url + '/', data=word, name=key_id)       
            time.sleep(2)
            print("{} 已修改完毕\n".format(word))         
        else:
            print("{} 未建立!\n".format(eword))
自定义函数 delete data ,实现单词的删除。
def delete_data():
    while True:
        eword =input("请输入要删除的英文单词(Enter==>停止输入)")
        if eword=="":
            break
        key_id = CkeckKey(eword)   
        if key_id != "":      # 判断键是否存在
            print("确定删除{}的数据!:".format(datas.get(key_id)))
            yn=input("(Y/N)?")
            if (yn=="Y" or yn=="y"):
                fb.delete(url + '/' + key_id,None)
                datas.pop(key_id)
                print("数据删除完毕\n")
        else:
            print("{} 单词不存在!\n".format(eword))
创建 Firebase 数据库连接 。
### 主程序从这里开始 ###

import time,os
from firebase import firebase

url = 'https://chiouapp01-74bde.firebaseio.com/English'
fb = firebase.FirebaseApplication(url, None)
datas=fb.get(url, None)

while True:
    menu()
    choice = input("请输入您的选择:")
    try:
        choice = int(choice)
        if choice==1:
            search_data()
        elif choice==2:
            input_data()
        elif choice==3:
            disp_data()
        elif choice==4:
            edit_data()
        elif choice==5:
            delete_data()
        else:
            break
    except:    
        print("\n非法按键!")
        time.sleep(1)
print("程序执行完毕!")