最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

调用Google的API接口翻译文章

XAMPP相关 中文小张 901浏览 0评论

运行的效果如下:
Snap62

源码如下:

1 import requests
2 from bs4 import BeautifulSoup
3
4
5 def getHTMLText(url):
6     try:
7         r = requests.get(url, timeout=30)
8         r.raise_for_status()
9         return r.text
10     except:
11         print("Get HTML Text Failed!")
12         return 0
13
14
15 def google_translate_EtoC(to_translate, from_language="en", to_language="ch-CN"):
16     # 根据参数生产提交的网址
17     base_url = "https://translate.google.cn/m?hl={}&sl={}&ie=UTF-8&q={}"
18     url = base_url.format(to_language, from_language, to_translate)
19
20     # 获取网页
21     html = getHTMLText(url)
22     if html:
23         soup = BeautifulSoup(html, "html.parser")
24
25     # 解析网页得到翻译结果
26     try:
27         result = soup.find_all("div", {"class": "t0"})[0].text
28     except:
29         print("Translation Failed!")
30         result = ""
31
32     return result
33
34
35 def google_translate_CtoE(to_translate, from_language="ch-CN", to_language="en"):
36     # 根据参数生产提交的网址
37     base_url = "https://translate.google.cn/m?hl={}&sl={}&ie=UTF-8&q={}"
38     url = base_url.format(to_language, from_language, to_translate)
39
40     # 获取网页
41     html = getHTMLText(url)
42     if html:
43         soup = BeautifulSoup(html, "html.parser")
44
45     # 解析网页得到翻译结果
46     try:
47         result = soup.find_all("div", {"class": "t0"})[0].text
48     except:
49         print("Translation Failed!")
50         result = ""
51
52     return result
53
54
55 def main():
56     while True:
57         inp = int(input("Chinese to Englisth is 1, English to Chinese is 2:    "))
58         if inp == 1:
59             words = input("请输入中文:    ")
60             print(google_translate_CtoE(words))
61         else:
62             words = input("Please input English:    ")
63             print(google_translate_EtoC(words))
64
65
66 main()

可参考的:
https://github.com/ssut/py-googletrans
https://github.com/terryyin/translate-python
https://github.com/yucongo/mgoogle_translate

转载请注明:XAMPP中文组官网 » 调用Google的API接口翻译文章

您必须 登录 才能发表评论!