已知支持英汉互译,理论上支持各种外文译中,自测,我没需求,就没测试
就几行代码,写的不优雅,但确实可用
package org.example;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
public class Main {
public static void main(String[] args) {
// 待翻译的关键词
String kerWord = "如果你有梦想的话,就必须捍卫它。那些一事无成的人总是想告诉你,你也成不了大器。如果你有理想的话,就要去努力实现。";
String url = "http://m.youdao.com/translate"; // 构建搜索URL
HttpRequest request = HttpRequest.post(url).form("inputtext", kerWord);
HttpResponse response = request.execute();
// 翻译结果的起始和结束文本
String startText = "<ul id=\"translateResult\">\n <li>";
String endText = "</li>\n </ul>";
String text = response.body();
// 获取翻译结果的起始和结束位置
int startIndex = text.indexOf(startText) + startText.length();
int endIndex = text.indexOf(endText);
// 判断是否找到翻译结果,并输出翻译结果
if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
String middleText = text.substring(startIndex, endIndex);
System.out.println("翻译结果为:" + middleText);
} else {
System.out.println("未找到匹配的起始和结束文本");
}
}
}
Python 版本:
from bs4 import BeautifulSoup as bs
from requests import post
def translate(s):
r = post("http://m.youdao.com/translate", data={"inputtext": s})
r.encoding = r.apparent_encoding
soup = bs(r.text, "html.parser")
ele = soup.find("ul", {"id": "translateResult"})
if ele:
li = ele.find("li")
if li:
return li.text
return ""
print(translate("hello"))