编程语言
首页 > 编程语言> > python实现小霸王词典

python实现小霸王词典

作者:互联网

python实现小霸王词典

在这里插入图片描述
效果图在这里插入图片描述

import requests


def fanyi(key):
    url = 'https://fanyi.baidu.com/sug'  # 将x语言翻译成y语言
    header = {'user_agent': 'Mozilla/5.0'}
    data = {
        'kw': key
    }
    dic1 = 'null'
    response = requests.post(url=url, data=data, headers=header)
    try:
        dic1 = response.json()['data'][0]['v']
    except:
        print('未找到对应得翻译')
    return dic1


def storagedic(dic):
    # 储存词汇
    while True:
        english = input("请输入录入的词汇(不录入输入-1退出该环节):")
        if english == '-1':
            break
        else:
            chinese = input("请输入对应的译文:")
            dic[english.lower()] = chinese
        print(dic)


def auto_storagedic(dic):
    # 根据百度翻译储存单词
    while True:
        english = input("请输入录入的词汇(不录入输入-1退出该环节):")
        if english == '-1':
            break
        else:
            chinese = fanyi(english)
            if chinese != 'null':
                dic[english.lower()] = chinese
                print(dic)


def translate_content(dic):  # 翻译句子
    while True:
        content = input('请输入需要翻译的内容:(-1退出)')
        if content == '-1':
            break
        list1 = content.split()
        for i in list1:
            i.lower()
            if i in dic:
                print(dic[i], end=' ')
            else:
                print(i, end=' ')
        print('\n')


if __name__ == '__main__':
    flag = 1
    dic = {}
    while flag:
        flag = int(input('1:录入单词(手动录入版),2:录入单词(自动录入版,需要联网), 3:离线翻译,4:在线翻译(支持各种语言,需要联网)0,或其他:退出:'))
        if flag == 1:
            storagedic(dic)
        elif flag == 2:
            print('速度受网速影响,如果没反应请等一会!')
            auto_storagedic(dic)
        elif flag == 3:
            print('单词不在字典中不翻译:(翻译中文时记得用空格隔开)')
            translate_content(dic)
        elif flag == 4:
            while True:
                xx = input('请输入需要翻译的内容(-1退出)')
                if xx == '-1':
                    break
                print(fanyi(xx))
        else:
            break

标签:python,english,dic,录入,flag,小霸王,print,input,词典
来源: https://blog.csdn.net/weixin_54883831/article/details/117775613