diff --git a/translation.txt b/translation.txt
new file mode 100644
index 0000000..c0421d8
--- /dev/null
+++ b/translation.txt
@@ -0,0 +1,973 @@
+import sys
+from PyQt5.QtWidgets import QApplication
+
+from PyQt5 import QtWidgets, QtCore, QtGui#绘制界面用到的模块
+
+from PyQt5.QtCore import Qt, QFile
+
+from faker import Faker#爬取有道翻译用到的模块
+import time
+import random
+import hashlib
+import requests
+
+from PyQt5.QtWidgets import QFileDialog, QDesktopWidget, QMainWindow # 调用系统文本选择框用到的模块
+
+import docx as docx#读取docx文档用到的模块
+
+import pyperclip#读取pdf文件用到的模块
+import pdfplumber as pdfplumber
+
+from win32com import client#将docx文件转化为pdf文件,doc文件转化为docx文件用到的模块
+
+import os#有关路径问题的模块
+
+from aip import AipOcr#调用百度文字识别用到的模块
+
+from PyQt5.QtGui import QIcon#设置图标用到的模块
+
+import execjs#运行js文件的模块
+
+from PyQt5.QtWidgets import QWidget#绘制悬浮窗用到的模块
+
+from PyQt5.QtGui import QCursor, QMouseEvent#设置鼠标的形状,重写移动事件用到的模块
+from PyQt5.QtCore import QPoint, QPropertyAnimation, QRect#设置动画用到的模块
+
+
+# import keyboard
+
+# from translation import Ui_MainWindow
+
+class Ui_MainWindow(object):
+ def setupUi(self, MainWindow):
+ MainWindow.setObjectName("MainWindow")
+ MainWindow.resize(1400, 1000)
+ self.centralwidget = QtWidgets.QWidget(MainWindow)
+ self.centralwidget.setObjectName("centralwidget")
+ self.widget = QtWidgets.QWidget(self.centralwidget)
+ self.widget.setGeometry(QtCore.QRect(10, 10, 1371, 941))
+ self.widget.setObjectName("widget")
+ self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.widget)
+ self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
+ self.verticalLayout_5.setObjectName("verticalLayout_5")
+ self.verticalLayout_4 = QtWidgets.QVBoxLayout()
+ self.verticalLayout_4.setObjectName("verticalLayout_4")
+ self.verticalLayout_2 = QtWidgets.QVBoxLayout()
+ self.verticalLayout_2.setObjectName("verticalLayout_2")
+ self.select_ = QtWidgets.QComboBox(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(12)
+ self.select_.setFont(font)
+ self.select_.setObjectName("select_")
+ self.select_.addItem("")
+ self.select_.addItem("")
+ self.verticalLayout_2.addWidget(self.select_)
+ self.select = QtWidgets.QComboBox(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(12)
+ self.select.setFont(font)
+ self.select.setObjectName("select")
+ self.select.addItem("")
+ self.select.addItem("")
+ self.verticalLayout_2.addWidget(self.select)
+ self.verticalLayout_4.addLayout(self.verticalLayout_2)
+ self.verticalLayout_3 = QtWidgets.QVBoxLayout()
+ self.verticalLayout_3.setObjectName("verticalLayout_3")
+ self.language = QtWidgets.QComboBox(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(12)
+ self.language.setFont(font)
+ self.language.setObjectName("language")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.language.addItem("")
+ self.verticalLayout_3.addWidget(self.language)
+ self.language_ = QtWidgets.QComboBox(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(12)
+ self.language_.setFont(font)
+ self.language_.setObjectName("language_")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.language_.addItem("")
+ self.verticalLayout_3.addWidget(self.language_)
+ self.verticalLayout_4.addLayout(self.verticalLayout_3)
+ self.verticalLayout_5.addLayout(self.verticalLayout_4)
+ self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
+ self.horizontalLayout_3.setObjectName("horizontalLayout_3")
+ self.translation = QtWidgets.QTextEdit(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(16)
+ self.translation.setFont(font)
+ self.translation.setObjectName("translation")
+ self.horizontalLayout_3.addWidget(self.translation)
+ self.translationresult = QtWidgets.QTextBrowser(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(16)
+ self.translationresult.setFont(font)
+ self.translationresult.setObjectName("translationresult")
+ self.horizontalLayout_3.addWidget(self.translationresult)
+ self.verticalLayout_5.addLayout(self.horizontalLayout_3)
+ self.verticalLayout = QtWidgets.QVBoxLayout()
+ self.verticalLayout.setObjectName("verticalLayout")
+ self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
+ self.horizontalLayout_2.setObjectName("horizontalLayout_2")
+ self.translate = QtWidgets.QPushButton(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(16)
+ self.translate.setFont(font)
+ self.translate.setObjectName("translate")
+ self.horizontalLayout_2.addWidget(self.translate)
+ self.clear = QtWidgets.QPushButton(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(16)
+ self.clear.setFont(font)
+ self.clear.setObjectName("clear")
+ self.horizontalLayout_2.addWidget(self.clear)
+ self.verticalLayout.addLayout(self.horizontalLayout_2)
+ self.horizontalLayout = QtWidgets.QHBoxLayout()
+ self.horizontalLayout.setObjectName("horizontalLayout")
+ self.copy = QtWidgets.QPushButton(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(16)
+ self.copy.setFont(font)
+ self.copy.setObjectName("copy")
+ self.horizontalLayout.addWidget(self.copy)
+ self.paste = QtWidgets.QPushButton(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(16)
+ self.paste.setFont(font)
+ self.paste.setObjectName("paste")
+ self.horizontalLayout.addWidget(self.paste)
+ self.signup = QtWidgets.QPushButton(self.widget)
+ font = QtGui.QFont()
+ font.setPointSize(16)
+ self.signup.setFont(font)
+ self.signup.setObjectName("signup")
+ self.horizontalLayout.addWidget(self.signup)
+ self.verticalLayout.addLayout(self.horizontalLayout)
+ self.verticalLayout_5.addLayout(self.verticalLayout)
+ MainWindow.setCentralWidget(self.centralwidget)
+ self.menubar = QtWidgets.QMenuBar(MainWindow)
+ self.menubar.setGeometry(QtCore.QRect(0, 0, 1400, 26))
+ self.menubar.setObjectName("menubar")
+ self.menu = QtWidgets.QMenu(self.menubar)
+ self.menu.setObjectName("menu")
+ MainWindow.setMenuBar(self.menubar)
+ self.statusbar = QtWidgets.QStatusBar(MainWindow)
+ self.statusbar.setObjectName("statusbar")
+ MainWindow.setStatusBar(self.statusbar)
+ self.a_open_file = QtWidgets.QAction(MainWindow)
+ self.a_open_file.setObjectName("a_open_file")
+ self.a_save_file = QtWidgets.QAction(MainWindow)
+ self.a_save_file.setObjectName("a_save_file")
+ self.a_about_ = QtWidgets.QAction(MainWindow)
+ self.a_about_.setObjectName("a_about_")
+ self.menu.addAction(self.a_open_file)
+ self.menu.addAction(self.a_save_file)
+ self.menu.addAction(self.a_about_)
+ self.menubar.addAction(self.menu.menuAction())
+
+ self.retranslateUi(MainWindow)
+ self.a_open_file.triggered.connect(self.open_file)
+ self.a_save_file.triggered.connect(self.save_file)
+ self.a_about_.triggered.connect(self.about_)
+ self.translate.clicked.connect(self.fanyi)
+ self.clear.clicked.connect(self.translationresult.clear)
+ self.clear.clicked.connect(self.translation.clear)
+ self.paste.clicked.connect(self.translation.paste)
+ self.copy.clicked.connect(self.copy_)
+ self.signup.clicked.connect(MainWindow.close)
+ self.translation.textChanged.connect(self.read_)
+ QtCore.QMetaObject.connectSlotsByName(MainWindow)
+
+ MainWindow.setWindowIcon(QIcon('./tubiao.ico'))#设置图标
+ self.translation.setStyleSheet("border-image:url(./background1.jpg);color:white")#设置文本框的背景图片和文字颜色
+ self.translationresult.setStyleSheet("border-image:url(./background.jpg);color:white")
+
+ # MainWindow.setStyleSheet("#MainWindow{border-image:url(./background.jpg);}")#设置窗体的背景图片(自适应)
+ # MainWindow.setStyleSheet("#MainWindow{background-image: url(./background.jpg);}")#设置窗体的背景图片
+
+ # self.translate.setStyleSheet("QPushButton{border-image: url(./background.jpg)}")#设置按钮的背景图片
+
+ # MainWindow.setWindowOpacity(0.5)#设置窗口透明度
+ # MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground)#设置窗口背景透明
+
+ # op = QtWidgets.QGraphicsOpacityEffect()#设置控件的透明度,透明度的值,0.0到1.0,最小值0是透明,1是不透明
+ # op.setOpacity(0.5)
+ # self.translate.setGraphicsEffect(op)
+ # self.translate.setAutoFillBackground(True)
+
+
+ MainWindow.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint)#设置窗体只有最小化和关闭按钮,固定窗体的大小
+ MainWindow.setStyleSheet("#MainWindow{background-color:black}")#设置窗体的背景颜色
+
+ self.language.setStyleSheet('background:black;color:white;')#设置控件的背景颜色和字体颜色
+ self.language_.setStyleSheet('background:black;color:white;')
+ self.select.setStyleSheet('background:black;color:white;')
+ self.select_.setStyleSheet('background:black;color:white;')
+
+ self.translate.setStyleSheet("QPushButton{background:black;color:white;border-radius:5px;}QPushButton:hover{background:white;color:gray;}")#设置控件的背景颜色和字体大小,以及复合事件
+ self.clear.setStyleSheet("QPushButton{background:black;color:white;border-radius:5px;}QPushButton:hover{background:white;color:gray;}")
+ self.copy.setStyleSheet("QPushButton{background:black;color:white;border-radius:5px;}QPushButton:hover{background:white;color:gray;}")
+ self.paste.setStyleSheet("QPushButton{background:black;color:white;border-radius:5px;}QPushButton:hover{background:white;color:gray;}")
+ self.signup.setStyleSheet("QPushButton{background:black;color:white;border-radius:5px;}QPushButton:hover{background:white;color:gray;}")
+
+ # MainWindow.setGeometry(200, 200, 1400, 1000)
+
+ # # 获取屏幕坐标系
+ # screen = QDesktopWidget().screenGeometry() # 得到屏幕的坐标系
+ # # 获取窗口坐标系
+ # size = MainWindow.geometry()
+ # newLeft = (screen.width() - size.width()) / 2 # 计算
+ # newTop = (screen.height() - size.height()) / 2
+ #
+ # MainWindow.move(int(newLeft), int(newTop)-42)
+
+ # 输出内容到textbrowser上
+ def printf(self, str):
+ self.translationresult.append(str)#在指定的区域显示提示信息
+ self.cursor = self.translationresult.textCursor()
+ self.translationresult.moveCursor(self.cursor.End)#光标移到最后,这样就会自动显示出来
+ QtWidgets.QApplication.processEvents()#一定加上这个功能,不然有卡顿
+
+ # 将内容复制到系统的剪切板上
+ def copy_(self):
+ pyperclip.copy(self.translationresult.toPlainText())
+
+ # 读取拖拽文件
+ def read_(self):
+ if self.translation.toPlainText().find('file:///') == 0:
+ self.translation.setText(self.translation.toPlainText().replace('file:///', ''))
+ flag = os.path.splitext(self.translation.toPlainText())[1]#获取路径中的文件类型
+ if flag == '.jpg' or flag == '.png':
+ if self.select.currentText() == '图片翻译':
+ imgs = self.translation.toPlainText()
+ global imgdict#定义全局变量
+ global imgpath
+ imgdict[imgpath] = imgs
+ self.translation.setText('')
+
+ self.translation.append('')#将图片显示到textedit上
+
+ self.fanyi()
+ # jpg = QtGui.QPixmap(imgs).scaled(self.label.width(), self.label.height())#将图片显示到标签上(自适应)
+ # self.label.setPixmap(jpg)
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ elif flag == '.txt':
+ if self.select.currentText() == '文字翻译':
+ txtbefore = self.translation.toPlainText()
+ self.translation.setText('')
+
+ f1 = QFile(txtbefore)#创建文件对象,不创建文件对象也不报错 也可以读文件和写文件
+ f2 = open(str(txtbefore), "r", encoding='UTF-8')#打开路径所对应的文件, "r"以只读的方式 也是默认的方式
+ txtafter = f2.read()#获取读取docx文件的内容
+ self.translation.setText(txtafter)
+ f2.close()
+
+ self.fanyi()
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ elif flag == '.docx':
+ if self.select.currentText() == '文字翻译':
+ docxbefore = self.translation.toPlainText()
+ self.translation.setText('')
+
+ docxafter = docx.Document(str(docxbefore))#定义对象
+
+ for i in range(len(docxafter.paragraphs)):#将docx文件中的内容输出到textedit上
+ self.translation.append(docxafter.paragraphs[i].text)
+
+ self.fanyi()
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ elif flag == '.doc':
+ if self.select.currentText() == '文字翻译':
+ wordss = client.Dispatch("Word.Application")
+ docbefore = self.translation.toPlainText()
+ self.translation.setText('')
+
+ docs = wordss.Documents.Open(docbefore)
+ zhuanhua = os.path.splitext(docbefore)[0] + str(random.randint(1, 248)) + '.docx'
+ docs.SaveAs(zhuanhua, 16)#使用参数16表示将doc转换成docx
+ docs.Close()
+ wordss.Quit()
+ file2 = docx.Document(zhuanhua)
+ for i in range(len(file2.paragraphs)):
+ self.translation.append(file2.paragraphs[i].text)
+ os.remove(zhuanhua)#删除转化后的docx文件
+
+ self.fanyi()
+
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ elif flag == '.pdf':
+ if self.select.currentText() == '文字翻译':
+ pdfbefore = self.translation.toPlainText()
+ self.translation.setText('')
+
+ pdfafter = pdfplumber.open(pdfbefore)#打开
+ page = pdfafter.pages#获取pdf文件中所有页的内容
+
+ for i in page:#将pdf文件中所有页内容输出到textedit
+ self.translation.append(i.extract_text())
+
+ self.fanyi()
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+ else:
+ self.translation.setText("暂不提供读取此类型的文件!")
+ else:
+ pass
+
+ # 读取各种文件
+ def open_file(self):
+ self.translation.setText('')
+
+ fileName, fileType = QFileDialog.getOpenFileName(self, "读取文件", "./","读取的文件类型(*.txt);;读取的文件类型(*.docx);;读取的文件类型(*.doc);;读取的文件类型(*.pdf);;读取的文件类型(*.jpg);;读取的文件类型(*.png)")#文件选择框
+ if fileName:
+ flag2 = os.path.splitext(fileName)[1]
+ if flag2 == '.txt':
+ if self.select.currentText() == '文字翻译':
+ txts = fileName
+
+ f3 = QFile(txts)
+ f4 = open(txts, "r", encoding='UTF-8')
+ data = f4.read()
+ self.translation.setText(data)
+ f4.close()
+
+ self.fanyi()
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ elif flag2 == '.docx':
+ if self.select.currentText() == '文字翻译':
+ docxs = fileName
+
+ file = docx.Document(str(docxs))
+ for i in range(len(file.paragraphs)):
+ self.translation.append(file.paragraphs[i].text)
+
+ self.fanyi()
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+
+ elif flag2 == '.doc':
+ if self.select.currentText() == '文字翻译':
+ words = client.Dispatch("Word.Application")
+ doc = words.Documents.Open(fileName)
+ zhuanhua1 = os.path.splitext(fileName)[0] + str(random.randint(1, 248)) + '.docx'
+ doc.SaveAs(zhuanhua1, 16)
+ doc.Close()
+ words.Quit()
+
+ file1 = docx.Document(zhuanhua1)
+ for i in range(len(file1.paragraphs)):
+ self.translation.append(file1.paragraphs[i].text)
+
+ self.fanyi()
+
+ os.remove(zhuanhua1)
+
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ elif flag2 == '.pdf':
+ if self.select.currentText() == '文字翻译':
+ pdfs = pdfplumber.open(fileName)
+ pages = pdfs.pages
+ for i in pages:
+ self.translation.append(i.extract_text())
+
+ self.fanyi()
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ elif flag2 == '.jpg' or flag2 == '.png':
+ if self.select.currentText() == '图片翻译':
+ global imgdict
+ global imgpath
+
+ imgdict[imgpath] = fileName
+ self.translation.setText('')
+
+ self.fanyi()
+ else:
+ self.translation.setText("读取的文件类型与翻译的文件类型不一致!")
+
+ else:
+ self.translation.setText("暂不支持读取此类型文件!")
+
+ # 保存各种文件
+ def save_file(self):
+ fileName1, fileType1 = QFileDialog.getSaveFileName(self, "保存文件", "./","保存的文件类型(*.txt);;保存的文件类型(*.docx);;保存的文件类型(*.pdf)")
+ if fileName1:
+ flag1 = os.path.splitext(fileName1)[1]
+ if flag1 == '.txt':
+ f5 = open(str(fileName1), "a+", encoding='UTF-8')
+ f5.write(self.translation.toPlainText() + '\n' + self.translationresult.toPlainText())
+ f5.close()
+
+ elif flag1 == '.docx':
+ docx1 = docx.Document()
+ docx1.add_paragraph(self.translation.toPlainText() + '\n' + self.translationresult.toPlainText())#增加一个paragraph
+ docx1.save(fileName1)
+
+ elif flag1 == '.pdf':
+ if os.path.exists(fileName1):
+ os.remove(fileName1)
+
+ docx2 = docx.Document()
+ docx2.add_paragraph(self.translation.toPlainText() + '\n' + self.translationresult.toPlainText())
+ zhuanhua2 = os.path.splitext(fileName1)[0] + str(random.randint(1, 248)) + '.docx'
+ docx2.save(zhuanhua2)
+
+ wordsss = client.DispatchEx("Word.Application")#将生成的docx文件转化为pdf文件
+ worddoc = wordsss.Documents.Open(zhuanhua2, ReadOnly=1)
+ worddoc.SaveAs(fileName1, FileFormat=17)
+ worddoc.Close()
+ os.remove(zhuanhua2)
+
+ else:
+ self.translation.setText("暂不支持保存此类型文件!")
+
+ # 读取软件说明
+ def about_(self):
+ self.translation.setText('')
+
+ f6 = QFile('./说明.txt')
+ f7 = open('./说明.txt', "r", encoding='UTF-8')
+ data1 = f7.read()
+ self.translation.setText(data1)
+ f7.close()
+
+ def fanyi(self):
+ start = time.time()#记录开始翻译时的时间
+ global imgdict
+ global imgpath
+
+ if self.select.currentText() == '图片翻译':
+ if imgdict[imgpath] != 0:
+ self.translation.setText('')
+
+ appId, apiKey, secretKey = ['24934744', '2X0jHwt9xQTPdDSK98UDSmuK', 'PEGjDcvsg9hmZrWyvI7oTrerHmB4lCeg']#此处填入在百度云控制台处获得的appId, apiKey, secretKey的实际值
+ ocr = AipOcr(appId, apiKey, secretKey)#创建ocr对象
+ imgs_ = open(imgdict[imgpath], 'rb')
+ imgs_word = imgs_.read()
+ res = ocr.basicGeneral(imgs_word)
+
+ imgdict[imgpath] = 0
+
+ for j in range(len(res['words_result'])):#输出识别图片后的内容
+ self.translation.append(res['words_result'][j]['words'])
+ else:
+ self.translation.setText("检测到没有导入图片,请导入图片后再进行翻译!")
+
+ content = self.translation.toPlainText()
+
+ if content != '' and content != "检测到没有导入图片,请导入图片后再进行翻译!" and content != "输入的相应内容为空,请输入翻译内容!":
+ if len(content) > 5000:
+ self.translation.setText("")
+ self.translation.setText("翻译内容超过5000字,请减少翻译内容!")
+
+ elif self.select_.currentText() == '有道翻译':#实现爬取有道翻译
+ self.translationresult.setText("")
+
+ languagedict = {
+ '自动检测语言(有道翻译)': ['AUTO', 'AUTO'],
+ '中文-->英语': ['zh-CHS', 'en'],
+ '英语-->中文': ['en', 'zh-CHS'],
+ '中文-->日语': ['zh-CHS', 'ja'],
+ '日语-->中文': ['ja', 'zh-CHS'],
+ '中文-->韩语': ['zh-CHS', 'ko'],
+ '韩语-->中文': ['ko', 'zh-CHS'],
+ '中文-->法语': ['zh-CHS', 'fr'],
+ '法语-->中文': ['fr', 'zh-CHS'],
+ '中文-->德语': ['zh-CHS', 'de'],
+ '德语-->中文': ['de', 'zh-CHS'],
+ '中文-->俄语': ['zh-CHS', 'ru'],
+ '俄语-->中文': ['ru', 'zh-CHS'],
+ '中文-->西班牙语': ['zh-CHS', 'es'],
+ '西班牙语-->中文': ['es', 'zh-CHS'],
+ '中文-->葡萄牙语': ['zh-CHS', 'pt'],
+ '葡萄牙语-->中文': ['pt', 'zh-CHS'],
+ '中文-->意大利语': ['zh-CHS', 'it'],
+ '意大利语-->中文': ['it', 'zh-CHS'],
+ '中文-->越南语': ['zh-CHS', 'vi'],
+ '越南语-->中文': ['vi', 'zh-CHS'],
+ '中文-->印尼语': ['zh-CHS', 'id'],
+ '印尼语-->中文': ['id', 'zh-CHS'],
+ '中文-->阿拉伯语': ['zh-CHS', 'ar'],
+ '阿拉伯语-->中文': ['ar', 'zh-CHS'],
+ '中文-->荷兰语': ['zh-CHS', 'nl'],
+ '荷兰语-->中文': ['nl', 'zh-CHS'],
+ '中文-->泰语': ['zh-CHS', 'th'],
+ '泰语-->中文': ['th', 'zh-CHS']
+ }
+ language = self.language.currentText()#获得当前内容
+
+ url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
+
+ ua = Faker().user_agent()
+
+ headers = {
+ 'User-Agent': ua,
+ 'Host': 'fanyi.youdao.com',
+ 'Origin': 'http://fanyi.youdao.com',
+ 'Referer': 'http://fanyi.youdao.com/',
+ 'Cookie': 'YOUDAO_MOBILE_ACCESS_TYPE=1; OUTFOX_SEARCH_USER_ID=685199569@10.108.160.102; JSESSIONID=aaaxE_dUg26X_bLyaCxWx; ___rl__test__cookies=' + str(time.time() * 1000) + '; OUTFOX_SEARCH_USER_ID_NCOO=836327382.8014793'
+ }
+ ts = str(time.time() * 1000)#生成相关的三个参数
+ salt = ts + str(random.randint(0, 10))
+ the_str = "fanyideskweb" + content + salt + "Y2FYu%TNSbMCxc3t2u^XT"
+ md5 = hashlib.md5()
+ md5.update(the_str.encode('utf-8'))
+ sign = md5.hexdigest()
+
+ data = {
+ 'i': content,
+ 'from': languagedict[language][0],
+ 'to': languagedict[language][1],
+ 'smartresult': "dict",
+ 'client': "fanyideskweb",
+ 'salt': salt,
+ 'sign': sign,
+ 'lts': ts,
+ 'bv': "e2a78ed30c66e16a857c5b6486a1d326",
+ 'doctype': "json",
+ 'version': "2.1",
+ 'keyfrom': "fanyi.web",
+ 'action': "FY_BY_REALTlME",
+ }
+
+ response = requests.post(url, headers=headers, data=data).json()
+
+
+ if 'smartResult' in response.keys():#单词的翻译
+ for i in range(len(response['smartResult']['entries']) - 1):
+ self.printf(str(i + 1))
+ self.printf(response['smartResult']['entries'][i + 1])
+ self.printf("")
+ end1 = time.time()
+ self.printf("此次翻译所花费的时间为:" + str(int(end1 - start)) + "s")
+
+
+ else:
+ for j in range(len(response['translateResult'])):#句子、段落的翻译
+ result = ''
+ for k in range(len(response['translateResult'][j])):
+ result += response['translateResult'][j][k]['tgt']
+ self.printf(result)
+ self.printf("")
+
+ end2 = time.time()#记录翻译结束的时间
+ self.printf("此次翻译所花费的时间为:" + str(int(end2 - start)) + "s")
+
+ elif self.select_.currentText() == '百度翻译':#实现破解百度翻译
+ self.translationresult.setText("")
+
+ if len(content) < 10 and (self.language_.currentText() == '中文-->英语(百度翻译)' or self.language_.currentText() == '英语-->中文'):
+
+ url2 = "https://fanyi.baidu.com/sug"
+
+ data1 = {'kw': content}
+
+ response2 = requests.post(url2, data=data1).json()
+
+ for a in range(len(response2['data'])):#单词翻译
+ self.printf(str(a + 1))
+ self.printf(response2['data'][a]['v'] + response2['data'][a]['k'])
+ self.printf("")
+
+ end3 = time.time()
+ self.printf("此次翻译所花费的时间为:" + str(int(end3 - start)) + "s")
+
+ else:
+ languagedict_ = {
+ '中文-->英语(百度翻译)': ['zh', 'en'],
+ '英语-->中文': ['en', 'zh'],
+ '中文-->粤语': ['zh', 'yue'],
+ '粤语-->中文': ['yue', 'zh'],
+ '中文-->文言文': ['zh', 'wyw'],
+ '文言文-->中文': ['wyw', 'zh'],
+ '中文-->中文繁体': ['zh', 'cht'],
+ '中文繁体-->中文': ['cht', 'zh'],
+ '中文-->韩语': ['zh', 'kor'],
+ '中文-->法语': ['zh', 'fra'],
+ '中文-->德语': ['zh', 'de'],
+ '中文-->俄语': ['zh', 'ru'],
+ '中文-->西班牙语': ['zh', 'spa'],
+ '中文-->葡萄牙语': ['zh', 'pt'],
+ '中文-->意大利语': ['zh', 'it'],
+ '中文-->越南语': ['zh', 'vie'],
+ '中文-->印尼语': ['zh', 'id'],
+ '中文-->阿拉伯语': ['zh', 'ara'],
+ '中文-->荷兰语': ['zh', 'nl'],
+ '中文-->泰语': ['zh', 'th'],
+ '中文-->日语': ['zh', 'jp'],
+ '日语-->中文': ['jp', 'zh'],
+ '韩语-->中文': ['kor', 'zh'],
+ '法语-->中文': ['fra', 'zh'],
+ '德语-->中文': ['de', 'zh'],
+ '俄语-->中文': ['ru', 'zh'],
+ '西班牙语-->中文': ['spa', 'zh'],
+ '葡萄牙语-->中文': ['pt', 'zh'],
+ '意大利语-->中文': ['it', 'zh'],
+ '越南语-->中文': ['vie', 'zh'],
+ '印尼语-->中文': ['id', 'zh'],
+ '阿拉伯语-->中文': ['ara', 'zh'],
+ '荷兰语-->中文': ['nl', 'zh'],
+ '泰语-->中文': ['th', 'zh']
+ }
+
+ js = open("sign.js", "r")#生成相关的一个参数
+ run_js = execjs.compile(js.read())
+ sign = run_js.call("e", content)#e为函数名
+ js.close()
+
+ headers1 = {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0",
+ "Cookie": "BAIDUID=1142AB91A9B514C11E73BD742DC5FE5C:FG=1; BIDUPSID=1142AB91A9B514C1B99F81A532D2E655; PSTM=1634650823; BDRCVFR[gltLrB7qNCt]=mk3SLVN4HKm; delPer=0; PSINO=7; H_PS_PSSID=34444_34067_34712_34584_34517_34832_26350_34828_34868_34473_34672; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1634650973,1634651117; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1634651117; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; __yjs_duid=1_11c84809e4b85738cf11c598a4671c281634650972004"
+ }
+
+ data2 = {
+ 'from': languagedict_[self.language_.currentText()][0],
+ 'to': languagedict_[self.language_.currentText()][1],
+ 'query': content,
+ 'transtype': 'translang',
+ 'simple_means_flag': '3',
+ 'sign': sign,
+ 'token': 'd8ef57d577cfbac850d72d3d6dde0dfb',
+ 'domain': 'common',
+ }
+
+ url1 = "https://fanyi.baidu.com/v2transapi?from={}&to={}".format(languagedict_[self.language_.currentText()][0], languagedict_[self.language_.currentText()][1])
+
+ response1 = requests.post(url1, headers=headers1, data=data2).json()
+
+ for b in range(len(response1["trans_result"]['data'])):#句子、段落翻译
+ self.printf(response1["trans_result"]['data'][b]['dst'])
+ self.printf("")
+
+ end4 = time.time()
+ self.printf("此次翻译所花费的时间为:" + str(int(end4 - start)) + "s")
+
+ else:
+ self.translation.setText("")
+ self.translation.setText("输入的相应内容为空,请输入翻译内容!")
+
+ def retranslateUi(self, MainWindow):
+ _translate = QtCore.QCoreApplication.translate
+ MainWindow.setWindowTitle(_translate("MainWindow", "爬虫翻译"))
+ self.select_.setItemText(0, _translate("MainWindow", "有道翻译"))
+ self.select_.setItemText(1, _translate("MainWindow", "百度翻译"))
+ self.select.setItemText(0, _translate("MainWindow", "文字翻译"))
+ self.select.setItemText(1, _translate("MainWindow", "图片翻译"))
+ self.language.setItemText(0, _translate("MainWindow", "自动检测语言(有道翻译)"))
+ self.language.setItemText(1, _translate("MainWindow", "中文-->英语"))
+ self.language.setItemText(2, _translate("MainWindow", "英语-->中文"))
+ self.language.setItemText(3, _translate("MainWindow", "中文-->韩语"))
+ self.language.setItemText(4, _translate("MainWindow", "中文-->法语"))
+ self.language.setItemText(5, _translate("MainWindow", "中文-->德语"))
+ self.language.setItemText(6, _translate("MainWindow", "中文-->俄语"))
+ self.language.setItemText(7, _translate("MainWindow", "中文-->西班牙语"))
+ self.language.setItemText(8, _translate("MainWindow", "中文-->葡萄牙语"))
+ self.language.setItemText(9, _translate("MainWindow", "中文-->意大利语"))
+ self.language.setItemText(10, _translate("MainWindow", "中文-->越南语"))
+ self.language.setItemText(11, _translate("MainWindow", "中文-->印尼语"))
+ self.language.setItemText(12, _translate("MainWindow", "中文-->阿拉伯语"))
+ self.language.setItemText(13, _translate("MainWindow", "中文-->荷兰语"))
+ self.language.setItemText(14, _translate("MainWindow", "中文-->泰语"))
+ self.language.setItemText(15, _translate("MainWindow", "中文-->日语"))
+ self.language.setItemText(16, _translate("MainWindow", "日语-->中文"))
+ self.language.setItemText(17, _translate("MainWindow", "韩语-->中文"))
+ self.language.setItemText(18, _translate("MainWindow", "法语-->中文"))
+ self.language.setItemText(19, _translate("MainWindow", "德语-->中文"))
+ self.language.setItemText(20, _translate("MainWindow", "俄语-->中文"))
+ self.language.setItemText(21, _translate("MainWindow", "西班牙语-->中文"))
+ self.language.setItemText(22, _translate("MainWindow", "葡萄牙语-->中文"))
+ self.language.setItemText(23, _translate("MainWindow", "意大利语-->中文"))
+ self.language.setItemText(24, _translate("MainWindow", "越南语-->中文"))
+ self.language.setItemText(25, _translate("MainWindow", "印尼语-->中文"))
+ self.language.setItemText(26, _translate("MainWindow", "阿拉伯语-->中文"))
+ self.language.setItemText(27, _translate("MainWindow", "荷兰语-->中文"))
+ self.language.setItemText(28, _translate("MainWindow", "泰语-->中文"))
+ self.language_.setItemText(0, _translate("MainWindow", "中文-->英语(百度翻译)"))
+ self.language_.setItemText(1, _translate("MainWindow", "英语-->中文"))
+ self.language_.setItemText(2, _translate("MainWindow", "中文-->粤语"))
+ self.language_.setItemText(3, _translate("MainWindow", "粤语-->中文"))
+ self.language_.setItemText(4, _translate("MainWindow", "中文-->文言文"))
+ self.language_.setItemText(5, _translate("MainWindow", "文言文-->中文"))
+ self.language_.setItemText(6, _translate("MainWindow", "中文-->中文繁体"))
+ self.language_.setItemText(7, _translate("MainWindow", "中文繁体-->中文"))
+ self.language_.setItemText(8, _translate("MainWindow", "中文-->韩语"))
+ self.language_.setItemText(9, _translate("MainWindow", "中文-->法语"))
+ self.language_.setItemText(10, _translate("MainWindow", "中文-->德语"))
+ self.language_.setItemText(11, _translate("MainWindow", "中文-->俄语"))
+ self.language_.setItemText(12, _translate("MainWindow", "中文-->西班牙语"))
+ self.language_.setItemText(13, _translate("MainWindow", "中文-->葡萄牙语"))
+ self.language_.setItemText(14, _translate("MainWindow", "中文-->意大利语"))
+ self.language_.setItemText(15, _translate("MainWindow", "中文-->越南语"))
+ self.language_.setItemText(16, _translate("MainWindow", "中文-->印尼语"))
+ self.language_.setItemText(17, _translate("MainWindow", "中文-->阿拉伯语"))
+ self.language_.setItemText(18, _translate("MainWindow", "中文-->荷兰语"))
+ self.language_.setItemText(19, _translate("MainWindow", "中文-->泰语"))
+ self.language_.setItemText(20, _translate("MainWindow", "中文-->日语"))
+ self.language_.setItemText(21, _translate("MainWindow", "日语-->中文"))
+ self.language_.setItemText(22, _translate("MainWindow", "韩语-->中文"))
+ self.language_.setItemText(23, _translate("MainWindow", "法语-->中文"))
+ self.language_.setItemText(24, _translate("MainWindow", "德语-->中文"))
+ self.language_.setItemText(25, _translate("MainWindow", "俄语-->中文"))
+ self.language_.setItemText(26, _translate("MainWindow", "西班牙语-->中文"))
+ self.language_.setItemText(27, _translate("MainWindow", "葡萄牙语-->中文"))
+ self.language_.setItemText(28, _translate("MainWindow", "意大利语-->中文"))
+ self.language_.setItemText(29, _translate("MainWindow", "越南语-->中文"))
+ self.language_.setItemText(30, _translate("MainWindow", "印尼语-->中文"))
+ self.language_.setItemText(31, _translate("MainWindow", "阿拉伯语-->中文"))
+ self.language_.setItemText(32, _translate("MainWindow", "荷兰语-->中文"))
+ self.language_.setItemText(33, _translate("MainWindow", "泰语-->中文"))
+ self.translation.setPlaceholderText(_translate("MainWindow", "请输入翻译内容:"))
+ self.translationresult.setPlaceholderText(_translate("MainWindow", "翻译结果:"))
+ self.translate.setText(_translate("MainWindow", "翻译"))
+ self.clear.setText(_translate("MainWindow", "清空"))
+ self.copy.setText(_translate("MainWindow", "复制"))
+ self.paste.setText(_translate("MainWindow", "粘贴"))
+ self.signup.setText(_translate("MainWindow", "退出"))
+ self.menu.setTitle(_translate("MainWindow", "文件"))
+ self.a_open_file.setText(_translate("MainWindow", "读取文件"))
+ self.a_save_file.setText(_translate("MainWindow", "保存文件"))
+ self.a_about_.setText(_translate("MainWindow", "关于软件"))
+
+class Window(QMainWindow,Ui_MainWindow):
+ def __init__(self):
+ super().__init__()
+ self.setupUi(self)
+
+ def keyPressEvent(self, event):
+ if (event.key() == Qt.Key_T or event.key() == Qt.Key_Enter):#这里event.key()显示的是按键的编码,按键事件对大小写不敏感
+ self.fanyi()
+ if (event.key() == Qt.Key_C):
+ self.copy_()
+ if (event.key() == Qt.Key_P):
+ self.translation.paste()
+ if (event.key() == Qt.Key_Q):
+ self.translation.clear()
+ self.translationresult.clear()
+ if (event.key() == Qt.Key_Escape):
+ self.close()
+ if (event.key() == Qt.Key_R):
+ self.open_file()
+ if (event.key() == Qt.Key_S):
+ self.save_file()
+
+ # 当需要组合键时,要很多种方式,这里举例为“shift+单个按键”,也可以采用shortcut、或者pressSequence的方法。
+ # if (event.key() == Qt.Key_P):
+ # if QApplication.keyboardModifiers() == Qt.ShiftModifier:
+ # print("shift + p")
+ # else :
+ # print("p")
+ #
+ # if (event.key() == Qt.Key_O) and QApplication.keyboardModifiers() == Qt.ShiftModifier:
+ # print("shift + o")
+
+ # # 响应鼠标事件
+ # def mousePressEvent(self, event):
+ # if event.button() == Qt.LeftButton:
+ # print("鼠标左键点击")
+ # elif event.button() == Qt.RightButton:
+ # print("鼠标右键点击")
+ # elif event.button() == Qt.MidButton:
+ # print("鼠标中键点击")
+
+class Ui_widget(object):
+ def setupUi(self, widget):
+ widget.setObjectName("widget")
+ widget.resize(80, 80)
+ self.pushButton = QtWidgets.QPushButton(widget)
+ self.pushButton.setGeometry(QtCore.QRect(10, 10, 60, 60))
+ self.pushButton.setObjectName("pushButton")
+
+ self.retranslateUi(widget)
+ self.pushButton.clicked.connect(self.xs)
+ QtCore.QMetaObject.connectSlotsByName(widget)
+
+ self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)#设置窗体去掉按钮、去边框、置顶
+ self.setAttribute(Qt.WA_TranslucentBackground)#设置窗体透明
+
+ self.pushButton.setStyleSheet("QPushButton{border-image:url(./xfc.jpg);color:white;border-radius:5px;}QPushButton:hover{border-image:url(./xfc1.jpg);color:gray;}")#设置控件的复合事件
+ self.pushButton.setCursor(QCursor(Qt.PointingHandCursor))#设置鼠标形状
+
+ #显示主界面
+ def xs(self):
+ global flag
+ if flag%2 == 0:
+ window.close()
+ else:
+
+ screen = QDesktopWidget().screenGeometry()# 获取屏幕坐标系
+ size = window.geometry() # 获取窗口坐标系
+ newLeft = (screen.width() - size.width()) / 2 # 计算
+ newTop = (screen.height() - size.height()) / 2
+ window.move(int(newLeft), int(newTop) - 42)
+
+ window.show()
+
+ flag+=1
+
+ def retranslateUi(self, widget):
+ _translate = QtCore.QCoreApplication.translate
+ widget.setWindowTitle(_translate("widget", "悬浮窗"))
+ self.pushButton.setText(_translate("widget", ""))
+
+class Windows(QWidget, Ui_widget):
+ def __init__(self):
+ super().__init__()
+ self._startPos = None
+ self._endPos = None
+ self._tracking = False
+ self.setupUi(self)
+
+ #重写键盘事件
+ def keyPressEvent(self, event):
+ if (event.key() == Qt.Key_Escape):#这里event.key()显示的是按键的编码,按键事件对大小写不敏感
+ self.close()
+ window.close()
+
+ # 重写移动事件
+ def mouseMoveEvent(self, e: QMouseEvent):
+ if self._tracking:
+ self._endPos = e.pos() - self._startPos
+ self.move(self.pos() + self._endPos)
+
+ def mousePressEvent(self, e: QMouseEvent):
+ if e.button() == Qt.RightButton:
+ self._startPos = QPoint(e.x(), e.y())
+ self._tracking = True
+
+ def mouseReleaseEvent(self, e: QMouseEvent):
+ if e.button() == Qt.RightButton:
+ self._tracking = False
+ self._startPos = None
+ self._endPos = None
+ #显示悬浮窗
+ def enterEvent(self, a0):
+ screen1 = QDesktopWidget().screenGeometry()
+ w1 = windows.geometry()
+ if w1.x() == -52:#左侧
+ self.startAnimation(54,0)
+
+ elif w1.y() == -52:#上方
+ self.startAnimation(0, 54)
+
+ elif w1.x() == screen1.width()-84+62:#右侧
+ self.startAnimation(-54, 0)
+
+ elif w1.y() == screen1.height()-84+62:#下方
+ self.startAnimation(0, -54)
+ # return super().enterEvent(a0)
+
+ #隐藏悬浮窗
+ def leaveEvent(self,a1):
+ screen = QDesktopWidget().screenGeometry()
+ w = windows.geometry()
+ if w.x() < 10 :#左侧
+ windows.move(10, w.y())
+ self.startAnimation(-62, 0)
+
+ elif w.y() < 10:#上方
+ windows.move(w.x(), 10)
+ self.startAnimation(0, -62)
+
+ elif screen.width() - w.x() < 84:#右侧
+ windows.move(screen.width()-84, w.y())
+ self.startAnimation(62, 0)
+
+ elif screen.height() - w.y() < 84:#下方
+ windows.move(w.x(), screen.height()-84)
+ self.startAnimation(0, 62)
+
+ def startAnimation(self,x,y):
+ animation = QPropertyAnimation(windows, b"geometry",self)
+ startpos = windows.geometry()
+ newpos = QRect(startpos.x() + x, startpos.y() + y, startpos.width(), startpos.height())
+ animation.setEndValue(newpos)
+ animation.setDuration(1000)
+ animation.start()
+
+
+if __name__ == '__main__':
+ imgpath = 'imgflag'
+ imgdict = {imgpath: 0}
+ readflag = 0
+ flag = 1
+
+ app = QApplication(sys.argv)
+ windows = Windows()
+ window = Window()
+ windows.show()
+
+ sys.exit(app.exec_())
\ No newline at end of file