今天分享一个终端下的翻译程序,又来解决简单的英汉单词句子互译问题。可能你会在机子上下个词霸的客户端,或者直接在浏览器上百度翻译,但对于习惯在终端操作的程序员来说,一个编辑器,一个终端才是标配。打开额外的东西实在太浪费时间和内存了,所以我就写了一个Python爬虫,直接在终端翻译,一劳永逸。临时写的,如有问题欢迎指正(如果网络慢的话,可能陈程序运行慢)。
首先你需要在你机子上下载Python3,requests库和BeautifulSoup库
代码:
import osimport requests as RS
from bs4 import BeautifulSoup as BS
url = "http://www.iciba.com/"
word = input("Please input what you want:")
while(word != "END"):
if word == "":
word = input("Please input what you want:")
try:
page = RS.get(url+word)
con = page.content
soup = BS(con,"lxml")
key = soup.find("h1",class_="keyword")
print("*"*20)
print(key.contents[0][20:])
lst = soup.find_all("li",class_="clearfix")
if len(lst) == 1:
ans = lst
else:
ans = lst[:-1]
for tag in ans:
for item in tag.contents:
if item.name == "span":
print(item.contents[0])
elif item.name == "p":
for i in item.contents:
if i != "\n":
print(i.contents[0])
print("*"*20)
except AttributeError as e:
print(e)
except Exception:
print("Something Wrong")
word = input("Please input what you want:")
if word == "cls":
os.system('cls')
word = ""
print("Bye-bye")