翻译工具包:txt文件专场(一)

百度接口详情

本人使用:标准版

  1. 需要使用延时函数控制上传速率,因为标准版QPS=1,但是不限制字符
  2. 可自行更改为更高级版的,同样免费,但是每个月有字符限制,不过足够学习使用了
  3. 本人已将自己的my_appid = '*************' cyber = '*************' 抹去需要的自个去百度翻译开放平台申请,简单快捷

流程

  1. 打开txt文件,先判断文件是否为空,不为空进入下一步
  2. 获取txt文件内的数据,按行输出,放入百度翻译接口进行上传获取,得到返回的译文
  3. 将获取到的已翻译译文放入译文文件中,先传入原文,换行传入译文,保存。

工具整体代码

# #!/usr/bin/env python
# # -*- coding: utf-8 -*-
# # @Time    : 2020/02/26 12:21
# # @Author  : Cxk
# # @File    : cxk.py

import requests
import string
import time
import hashlib
import json
import re
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter import filedialog
import threading
import datetime
import webbrowser

times = datetime.datetime.now()
times_str = datetime.datetime.strftime(times,'%Y-%m-%d %H:%M:%S')

api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate"
my_appid = '*************'
cyber = '*************'
lower_case = list(string.ascii_lowercase)

def save_error(cuowu):
    with open('error.txt','a') as file_handle:
        # .txt可以不自己新建,代码会自动新建
        file_handle.write(times_str)
        file_handle.write('\n')
        file_handle.write("函数: "+cuowu)     # 写入
        file_handle.write('\n')
        file_handle.write('\n')
    
    
def requests_for_dst(word,From,To):
    """
    word:翻译内容
    From:翻译语言
    To:返回语言
    'en':英语
    'zh':中文
    """
    try:
        salt = str(time.time())[:10]
        final_sign = str(my_appid)+word+salt+cyber
        final_sign = hashlib.md5(final_sign.encode("utf-8")).hexdigest()
        #区别en,zh构造请求参数
        paramas = {
                'q':word,
                'from':From,
                'to':To,
                'appid':'%s'%my_appid,
                'salt':'%s'%salt,
                'sign':'%s'%final_sign
                }
        my_url = api_url+'?appid='+str(my_appid)+'&q='+word+'&from='+'en'+'&to='+'zh'+'&salt='+salt+'&sign='+final_sign
        response = requests.get(api_url,params = paramas).content
        content = str(response,encoding = "utf-8")
        json_reads = json.loads(content)
    #     print(json_reads)
        return json_reads['trans_result'][0]['dst']
    except Exception as e:
        cuowu="requests_for_dst "+str(e)
        save_error(cuowu)
        
#先读取
#翻译
#写入
#需要设置延时,不然无法返回

def translation_text(path,oldstr,newstr):
    """
    path:原文文件路径
    oldstr:原文语句
    newstr:译文语句
    """
    try:
        path='%s_译文'%path[:-4]+".txt"
        with open(path,'a') as file_handle:
            file_handle.write(oldstr)
            file_handle.write('\n')
            file_handle.write(newstr)
            file_handle.write('\n')
    except Exception as e:
        cuowu="translation_text "+str(e)
        save_error(cuowu)
            
def original_text(path,From,To):
    """
    path:原文文件路径
    From:原文语言
    To:需要翻译成的语言
    """
    file=open(path)
    try:
        for i in file:
            if i=='\n':
                continue
            else:
                translation_text(path,i.strip('\n'),requests_for_dst(i.strip('\n'),From,To))
                time.sleep(1)
    except Exception as e:
        cuowu="original_text "+str(e)
        save_error(cuowu)
            
    file.close

class Rootpage(object):
    def __init__(self, master=None):
        self.root = master
        winWidth = 400
        winHeight = 200
        screenWidth = self.root.winfo_screenwidth()
        screenHeight = self.root.winfo_screenheight()

        x = int((screenWidth - winWidth) / 2)
        y = int((screenHeight - winHeight) / 2)
        # 设置窗口初始位置在屏幕居中
        self.root.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
        # 设置窗口图标
        # root.iconbitmap("./image/icon.ico")
        # 设置窗口宽高固定
        self.root.resizable(0, 0)
        self.Filepath=""
        self.createPage()

    
    def createPage(self):
        def open_url(event):
            webbrowser.open("https://me.csdn.net/Cxk___", new=0)
        Label(root,font=("微软雅黑", 12),text="点击联系作者@Cxk").pack()
        link=Label(root,font=("微软雅黑", 12),fg='blue',text="CSDN博客@半盏清茶℡")
        link.pack()
        link.bind("<Button-1>", open_url)
        Label(root,font=("微软雅黑", 10),text="").pack()
        Button(root,text='选择txt文件', bd =5,command=self.open_file).pack()
        Label(root,font=("微软雅黑", 5),text="").pack()
        Button(root,text='开始翻译', bd =5,command=self.fun).pack()
        

    def open_file(self):
        self.Filepath = filedialog.askopenfilename() #获得选择好的文件
        try:
            size = os.path.getsize(self.Filepath)
            if size == 0:
                showinfo(title='错误', message='你所选择的txt文件为空,请重新选择!')
            elif self.Filepath=="":
                showinfo(title='错误', message='你并未选择txt文件,请重新选择!')
            else:
                pass
        except Exception as e:
            cuowu="open_file "+str(e)
            save_error(cuowu)
        else:
            Label(root,font=("微软雅黑", 10),text=self.Filepath).pack()
            
    def start(self):
        showinfo(title='提示', message='翻译已开始,稍后完成会为你打开文件夹!')
        original_text(self.Filepath,'zh','en')
        path=os.path.abspath(os.path.join(self.Filepath,".."))#返回上一目录
        os.startfile(path)
        showinfo(title='提示', message='翻译已完成,已为你打开翻译文件所在文件夹!')
            
    def fun(self):
            th=threading.Thread(target=self.start)
            th.setDaemon(True)#守护线程
            th.start()

if __name__ == "__main__":
    root = Tk() 
    root.title('txt文档翻译') 
    Rootpage(root)
    root.mainloop() 

整体演示

新操作

点击label控件打开网页,思路来源,代码:

def open_url(event):
    webbrowser.open("https://me.csdn.net/Cxk___", new=0)
Label(root,font=("微软雅黑", 12),text="点击联系作者@Cxk").pack()
link=Label(root,font=("微软雅黑", 12),fg='blue',text="CSDN博客@半盏清茶℡")
link.pack()
link.bind("<Button-1>", open_url)

容错处理

  1. 将所有可能产生错误的地方进行错误收集

  2. 使用try-except

  3. 代码段

    try:
    
    except Exception as e:
            cuowu="requests_for_dst "+str(e)
            save_error(cuowu)
    def save_error(cuowu):
        with open('error.txt','a') as file_handle:
            # .txt可以不自己新建,代码会自动新建
            file_handle.write(times_str)
            file_handle.write('\n')
            file_handle.write("函数: "+cuowu)     # 写入
            file_handle.write('\n')
            file_handle.write('\n')

    error.txt文件

结语

  1. 最近想搞个翻译工具集,先搞了个txt文档翻译,有空再弄个word文档翻译

  2. 当然网上一堆这些工具,不过很多都有限制,超过限制就要付费,不过百度翻译好像不用,一直用它的网页版翻译文档,还挺好用的。做这些纯粹为了学习使用,实在太闲了,都快发霉了。

  3. 好像还有很多能改进的,不过暂时先这样

发布了22 篇原创文章 · 获赞 14 · 访问量 4398

猜你喜欢

转载自blog.csdn.net/Cxk___/article/details/104513856