[Visual Basic] 纯文本查看 复制代码
Option Explicit
Const API_KEY = "<这里要输入你自己申请的翻译api>"
Const API_URL = "http://api.niutrans.com/NiuTransServer/translation"
Dim inputText, translatedText
inputText = InputBox("请输入要翻译的中文或英文:", "中英文翻译")
If Trim(inputText) = "" Then
MsgBox "未输入任何内容。", vbExclamation, "提示"
WScript.Quit
End If
If Len(inputText) > 50 Then
MsgBox "输入内容不能超过 50 个字符,请重新输入。", vbExclamation, "提示"
WScript.Quit
End If
Dim srcLang, tgtLang
' 判断第一个非空字符的 Unicode 范围来推测语言
Dim firstChar, code
firstChar = Mid(Trim(inputText), 1, 1)
code = AscW(firstChar)
If code >= 19968 And code <= 40869 Then
srcLang = "zh"
tgtLang = "en"
Else
srcLang = "en"
tgtLang = "zh"
End If
translatedText = TranslateText(inputText, srclang, tgtlang)
If translatedText <> "" Then
MsgBox "翻译结果:" & vbCrLf & vbCrLf & inputText & vbCrLf & translatedText, vbInformation, "中英互译"
Else
MsgBox "翻译失败,请检查网络或API配置。", vbCritical, "错误"
End If
Function TranslateText(text, srcLang, tgtLang)
Dim http, postData, response, json, result
On Error Resume Next
Set http = CreateObject("MSXML2.XMLHTTP")
postData = "from=" & srcLang & "&to=" & tgtLang & "&apikey=" & API_KEY & "&src_text=" & URLEncodeUTF8(text)
http.Open "POST", API_URL, False
http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.Send postData
If http.Status = 200 Then
response = http.responseText
' 简单提取 tgt_text 内容
Dim startPos, endPos
startPos = InStr(response, """tgt_text"":""")
If startPos > 0 Then
startPos = startPos + Len("""tgt_text"":""")
endPos = InStr(startPos, response, """")
If endPos > startPos Then
result = Mid(response, startPos, endPos - startPos)
result = Replace(result, "\r\n", vbCrLf)
result = Replace(result, "\n", vbCrLf)
result = Replace(result, "\\", "\")
Else
result = "(未能提取翻译结果)"
End If
Else
result = "(未找到翻译字段)"
End If
Else
result = "(请求失败,状态码:" & http.Status & ")"
End If
If Err.Number <> 0 Then
result = "(发生错误:" & Err.Description & ")"
Err.Clear
End If
On Error GoTo 0
TranslateText = result
End Function
' URL编码函数
' UTF-8 URL 编码函数
Function URLEncodeUTF8(str)
Dim objStream, objStreamUtf8, bytes, i, hexChar
' 原始字符串 -> UTF-8 字节流
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 2 ' text
objStream.Mode = 3 ' read/write
objStream.Open
objStream.Charset = "UTF-8"
objStream.WriteText str
objStream.Position = 0
objStream.Type = 1 ' binary
bytes = objStream.Read
objStream.Close
' 转成 %XX 形式
URLEncodeUTF8 = ""
For i = 1 To LenB(bytes)
hexChar = Hex(AscB(MidB(bytes, i, 1)))
If Len(hexChar) = 1 Then hexChar = "0" & hexChar
' 0-9 / A-Z / a-z 不编码
If (AscB(MidB(bytes, i, 1)) >= 48 And AscB(MidB(bytes, i, 1)) <= 57) _
Or (AscB(MidB(bytes, i, 1)) >= 65 And AscB(MidB(bytes, i, 1)) <= 90) _
Or (AscB(MidB(bytes, i, 1)) >= 97 And AscB(MidB(bytes, i, 1)) <= 122) Then
URLEncodeUTF8 = URLEncodeUTF8 & Chr(AscB(MidB(bytes, i, 1)))
Else
URLEncodeUTF8 = URLEncodeUTF8 & "%" & hexChar
End If
Next
End Function