weixin_46237899 2021-11-25 00:07 采纳率: 0%
浏览 23

蹲一个python200行的翻译的ym

这里找到配置search包什么怎么样都安装不了

  • 写回答

1条回答 默认 最新

  • CSDN专家-黄老师 2021-11-25 21:55
    关注

    实际是通过翻译网站的API接口实现翻译功能,可以参考下

    import requests
    import random
    import hashlib
    import json
    import urllib
    import pyperclip
    from sys import exit
    from optparse import OptionParser
    
    
    APP_ID="**********"
    KEY="**********"
    
    # global option
    class Conf:
    
        DEFAULT = 1 # stanted
        FILE = 2 # file
        CLIPBOARD = 3 # clipboard
    
        langs = {
            "en": "英文",
            "zh": "中文",
            "yue": "粤语",
            "wyw": "文言文",
            "jp": "日语",
            "kor": "韩语",
            "fra": "法语",
            "spa": "西班牙语",
            "th": "泰语",
            "ara": "阿拉伯语",
            "ru": "俄语",
            "pt": "葡萄牙语",
            "de": "德语",
            "it": "意大利语",
            "el": "希腊语",
            "nl": "荷兰语",
            "pl": "波兰语",
            "bul": "保加利亚语",
            "est": "爱沙尼亚语",
            "dan": "丹麦语",
            "fin": "芬兰语",
            "cs": "捷克语",
            "rom": "罗马尼亚语",
            "slo": "斯洛文尼亚语",
            "swe": "瑞典语",
            "hu": "匈牙利语",
            "cht": "繁体中文",
            "vie": "越南语"
        }
    
        SYS_IN = DEFAULT
        SYS_OUT = DEFAULT
        trans_from = "en"
        trans_to = "zh"
        query_str = ""
        input_file = ""
        output_file = ""
    
    
    def printArgs():
        print(Conf.SYS_IN)
        print(Conf.SYS_OUT)
        print(Conf.trans_from)
        print(Conf.trans_to)
        print(Conf.query_str)
        print(Conf.input_file)
        print(Conf.output_file)
    
    
    def main():
        # init
        option_handle()
        # start query
        query()
    
    
    def option_handle():
        usage = "usage: %prog [option] arg"
        opt_parser = OptionParser()
        opt_parser.add_option(
            "-f", "--from",
            dest="trans_from",
            default="en",
            help="default=en\t\t\t\t\ten...english   zh...chinese --list show all language code."
        )
        opt_parser.add_option(
            "-t", "--to",
            dest="trans_to",
            default="zh",
            help="default=zh\t\t\t\t\ten...english   zh...chinese. --list show all language code."
        )
        opt_parser.add_option(
            "-p", "--paste",
            action="store_true",
            dest="paste",
            help="use cilpboard content."
        )
        opt_parser.add_option(
            "-i", "--inputfile",
            dest="in_file",
            help="type file path to input."
        )
        opt_parser.add_option(
            "-o", "--outputfile",
            dest="out_file",
            help="type file path to output."
        )
        opt_parser.add_option(
            "-q", "--query",
            dest="query_str",
            help="translate content."
        )
        opt_parser.add_option(
            "-c", "--clipboard",
            dest="copy",
            action="store_true",
            help="output to clipboard."
        )
        opt_parser.add_option(
            "-l", "--list",
            dest="list_all",
            action="store_true",
            help="show all language code."
        )
        (options, args) = opt_parser.parse_args()
        if options.list_all:
            print("all language code: ")
            for k, v in Conf.langs.items():
                print(k, " ", v)
            exit(0)
        if len(args) > 1:
            opt_parser.error("incorrent number of arguments")
            exit(0)
        # from
        if options.trans_from not in list(Conf.langs.keys()):
            opt_parser.error("invalid translate_from language code. --list show all code")
            exit(0)
        Conf.trans_from = options.trans_from
        # to
        if options.trans_to not in list(Conf.langs.keys()):
            opt_parser.error("invalid translata_to language code. --list show all code")
            exit(0)
        Conf.trans_to = options.trans_to
        # query
        if len(args) == 1:
            Conf.query_str = args[0]
        elif options.paste:
            Conf.SYS_IN = Conf.CLIPBOARD
            Conf.query_str = pyperclip.paste()
        elif options.in_file:
            Conf.SYS_IN = Conf.FILE
            Conf.input_file = options.in_file
            try:
                with open(Conf.input_file, "r+") as in_file:
                    for line in in_file.readlines():
                        Conf.query_str += line.replace("\n", " ")
            except:
                opt_parser.error("\n[error]: No such file: " + options.in_file)
        else:
            Conf.SYS_IN = Conf.CLIPBOARD
            Conf.query_str = pyperclip.paste()
        # out
        if options.copy:
            Conf.SYS_OUT = Conf.CLIPBOARD
        elif options.out_file:
            Conf.SYS_OUT = Conf.FILE
            Conf.output_file = options.out_file
        else:
            # Conf.SYS_OUT = Conf.DEFAULT
            pass
    
        
            
    
    
    def query() -> dict:
        try:
            resp = requests.get(url_handle(Conf.query_str, Conf.trans_from, Conf.trans_to), timeout=5)
            print_result(json.loads(resp.content))
        except requests.RequestException:
            print("[error] network is too slow.")
            exit(0)
        
    
    
    def url_handle(query_str: str, _from: str, _to: str) -> str:
        # 
        base_url = "https://fanyi-api.baidu.com/api/trans/vip/translate?"
        form_data = {
            "q": query_str,
            "from": _from,
            "to": _to,
            "appid": APP_ID,
            "salt": str(random.randint(1000000, 99999999))
        }
        form_data['sign'] = get_md5_token(APP_ID + form_data["q"] + form_data["salt"] + KEY)
        form_data['q'] = urllib.parse.quote(form_data['q'])
        for k, v in form_data.items():
            base_url += k + "=" + v + "&"
        return base_url[:-1]
    
    
    def print_result(data: dict):
        try:
            source_str = data['trans_result'][0]['src']
            dest_str = data['trans_result'][0]['dst']
        except Exception:
            print("[error] please check your arguments and try again.")
            exit(0)
        if Conf.SYS_OUT == Conf.DEFAULT:
            print("[source]: ", source_str)
            print("[dest]: ", dest_str)
        elif Conf.SYS_OUT == Conf.FILE:
            try:
                with open(Conf.output_file, "w+") as of:
                    of.write("[source]\n")
                    of.write(source_str + "\n")
                    of.write("[dest]\n")
                    of.write(dest_str)
            except PermissionError:
                print("[error] Permission denied: ", Conf.output_file)
        else:
            pyperclip.copy(dest_str)
    
    
    def get_md5_token(key: str) -> str:
        _md5 = hashlib.md5()
        _md5.update(key.encode("utf-8"))
        return _md5.hexdigest()
    
    
    if __name__ == '__main__':
        main()
    
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月25日

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境