首先展示一下最终的实现结果:源代码下载
这里调用的是百度的翻译接口,我们通过访问百度翻译 可以获得对应的url 和请求数据。。
第一步: 我们打开百度翻译的网址,在翻译这边随便输入一个中文,可以发现下面那个请求包。。然后打开,会发现对应的url 和请求数据。等会我们模拟浏览器进行发送请求。。然后获取翻译的内容。
第二步:我们先简单做一个不带界面的翻译代码
做了两个函数,一个是中文翻译为英文(函数translate()),一个是英文翻译为中文(函数translate1())。 url就是我们上面观察得到的url, 前面的v2版本号,我们在请求的url中去掉了。。接下来是data,这就是请求数据。。word就是我们带翻译的文本。最后会返回一个json格式的数据。。然后将数据提取出来即可。。
import requests
def translate(word):
url = 'https://fanyi.baidu.com/transapi'
data = {
'from': 'zh',
'to': 'en',
'query': word,
'transtype': 'realtime',
'simple_means_flag': '3',
'sign': '325815.7046',
'token': '9b1b599bf1303d7d525833a9e17579bb'
}
response = requests.post(url, data=data).json() # 将获取的数据转换为json格式
print(response['data'][0]['result'][0][1])
def translate2(word):
url = 'https://fanyi.baidu.com/transapi'
data = {
'from': 'en',
'to': 'zh',
'query': word,
'transtype': 'realtime',
'simple_means_flag': '3',
'sign': '325815.7046',
'token': '9b1b599bf1303d7d525833a9e17579bb'
}
response = requests.post(url, data=data).json() # 将获取的数据转换为json格式
print(response['data'][0]['result'][0][1])
if __name__ == '__main__':
sign = input("你想进行的是中翻英还是英翻中(中翻英按1,英翻中按2):")
if sign == '1':
word = input("请输入要翻译的中文:")
translate(word)
elif sign == '2':
word = input("请输入要翻译的英文:")
translate2(word)
else:
print("滚,你输入错了!!!")
输出结果展示:
第三步:我们借用PyQt设置一个界面。然后设置两个按钮,将这两个翻译函数绑定到按钮上即可。。
①:设置界面,通过QtDesign。。然后转换为下面的python代码
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Translate.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 601)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.zh2en = QtWidgets.QPushButton(self.centralwidget)
self.zh2en.setGeometry(QtCore.QRect(220, 470, 81, 61))
font = QtGui.QFont()
font.setFamily("Arial")
font.setBold(False)
font.setWeight(50)
self.zh2en.setFont(font)
self.zh2en.setObjectName("zh2en")
self.en2zh = QtWidgets.QPushButton(self.centralwidget)
self.en2zh.setGeometry(QtCore.QRect(360, 470, 81, 61))
self.en2zh.setObjectName("en2zh")
self.clearBtn = QtWidgets.QPushButton(self.centralwidget)
self.clearBtn.setGeometry(QtCore.QRect(490, 470, 91, 61))
self.clearBtn.setObjectName("clearBtn")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(310, 40, 161, 31))
font = QtGui.QFont()
font.setFamily("楷体")
font.setPointSize(26)
self.label.setFont(font)
self.label.setObjectName("label")
self.textEdit1 = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit1.setGeometry(QtCore.QRect(90, 120, 271, 301))
self.textEdit1.setObjectName("textEdit1")
self.textEdit2 = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit2.setGeometry(QtCore.QRect(449, 121, 271, 301))
self.textEdit2.setObjectName("textEdit2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.zh2en.setText(_translate("MainWindow", "中文翻译英文"))
self.en2zh.setText(_translate("MainWindow", "英文翻译中文"))
self.clearBtn.setText(_translate("MainWindow", "清空"))
self.label.setText(_translate("MainWindow", "小狗翻译"))
self.textEdit1.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">请输入翻译的内容</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"))
self.textEdit2.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">输出结果</p></body></html>"))
②:接下来在同级目录下建立一个python文件callTranslate.py (这个名字是随便起的)实现调用界面,并给按钮绑定槽函数。。实现如下:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import requests
import sys
from Translate import Ui_MainWindow
class Win(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Win, self).__init__(parent)
self.setupUi(self)
self.zh2en.clicked.connect(self.zh2enfun)
self.en2zh.clicked.connect(self.en2zhfun)
self.clearBtn.clicked.connect(self.clearinfo)
def zh2enfun(self):
'''中文翻译为英文'''
word = self.textEdit1.toPlainText()
url = 'https://fanyi.baidu.com/transapi'
data = {
'from': 'zh',
'to': 'en',
'query': word,
'transtype': 'realtime',
'simple_means_flag': '3',
'sign': '325815.7046',
'token': '9b1b599bf1303d7d525833a9e17579bb'
}
response = requests.post(url, data=data).json() # 将获取的数据转换为json格式
info = response['data'][0]['result'][0][1]
self.textEdit2.setText(info)
def en2zhfun(self):
'''英文翻译为中文'''
word = self.textEdit1.toPlainText()
url = 'https://fanyi.baidu.com/transapi'
data = {
'from': 'en',
'to': 'zh',
'query': word,
'transtype': 'realtime',
'simple_means_flag': '3',
'sign': '325815.7046',
'token': '9b1b599bf1303d7d525833a9e17579bb'
}
response = requests.post(url, data=data).json() # 将获取的数据转换为json格式
info = response['data'][0]['result'][0][1]
self.textEdit2.setText(info)
def clearinfo(self):
self.textEdit1.clear()
self.textEdit2.clear()
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Win()
win.setObjectName("MainWindow") # 为主窗口设置对象名 为了在下面设置背景颜色
win.setStyleSheet("#MainWindow{border-image:url(./data/background.jpg);}")
win.show()
sys.exit(app.exec_())
最后执行callTranslate.py 输出结果: