Rust 调用bing 翻译接口

180it 2024-10-29 PM 138℃ 0条
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
regex = "1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }

use reqwest::Client;
use regex::Regex;
use serde_json::Value;
use std::collections::HashMap;

async fn trans(word: &str) -> Result<String, Box<dyn std::error::Error>> {
    let client = Client::new();
    let flg = Regex::new(r"[\u4e00-\u9f5a]")?.is_match(word);
    let (from_word, to_word) = if flg { ("zh-Hans", "en-GB") } else { ("en-GB", "zh-Hans") };

    let uri = "https://cn.bing.com/translator";
    let gi = client.get(uri).send().await?.text().await?;
    let ig_re = Regex::new(r#"IG:"(.*?)""#)?;
    let token_re = Regex::new(r#"params_AbusePreventionHelper = (.*?);"#)?;

    let ig = ig_re.captures(&gi).ok_or("Failed to capture IG")?[1].to_string();
    let token = token_re.captures(&gi).ok_or("Failed to capture token")?[1].to_string();
    let token_replaced = token.replace("[", ""); // 将临时值绑定到变量上
    let tokens: Vec<&str> = token_replaced.split(',').collect();
    let t = &tokens[1][1..33];
    let url = format!("https://cn.bing.com/ttranslatev3?isVertical=1&&IG={}&IID=translator.5027", ig);

    let mut data = HashMap::new();
    data.insert("fromLang", from_word);
    data.insert("text", word);
    data.insert("to", to_word);
    data.insert("token", t);
    data.insert("key", tokens[0]);
    data.insert("tryFetchingGenderDebiasedTranslations", "true");

    let response = client.post(&url)
        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36")
        .form(&data)
        .send()
        .await?;

    let response_text = response.text().await?;
    let json: Value = serde_json::from_str(&response_text)?;
    let translated_text = json[0]["translations"][0]["text"].as_str().ok_or("Failed to get translation")?.to_string();

    Ok(translated_text)
}

#[tokio::main]
async fn main() {
    let word = "你说你,想要逃,剩下空心要不要";
    match trans(word).await {
        Ok(result) => println!("{}", result),
        Err(e) => println!("翻译失败: {}", e),
    }
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

Rust 调用bing 翻译接口