ASP Google的translate API代碼

來源:互聯網
上載者:User

直接看代碼: 複製代碼 代碼如下:Class GoogleTranslator
sub Class_Initialize()
RURI="http://translate.google.com/translate_t?langpair={0}&text={1}"
End Sub
Private Opt_ '
Property Get Opt
Opt=Opt_
End Property
Property Let Opt(Opt_s)
Opt_=Opt_s
End Property
Private RURI
Function AnalyzeChild(patrn,texts,IPos)
Dim regEx, Match, Matches
Set regEx = New RegExp
regEx.IgnoreCase = true
regEx.Global = True
regEx.Pattern = patrn
regEx.Multiline = True
Dim RetStr
Set Matches = regEx.Execute(texts)
If(Matches.Count > 0)Then RetStr= Matches(0).SubMatches(IPos)
AnalyzeChild=RetStr
Set regEx =Nothing
End Function
Function getHTTPPage(url)
dim objXML
set objXML=server.createobject("MSXML2.XMLHTTP")'定義
objXML.open "GET",url,false'開啟
objXML.send()'發送
If objXML.readystate<>4 then
exit function
End If
getHTTPPage=BytesToBstr(objXML.responseBody)
set objXML=nothing'關閉
if err.number<>0 then err.Clear
End Function
Function BytesToBstr(body)
dim objstream
set objstream = Server.CreateObject("adodb.stream")
objstream.Type = 1
objstream.Mode =3
objstream.Open
objstream.Write body
objstream.Position = 0
objstream.Type = 2
objstream.Charset = "utf-8"
'轉換原來預設的UTF-8編碼轉換成GB2312編碼,否則直接用XMLHTTP調用有中文字元的網頁得到的將是亂碼
BytesToBstr = objstream.ReadText
objstream.Close
set objstream = nothing
End Function
Public Function GetText(str)
If(isempty(str)) Then Exit Function
Dim newUrl,Rs
newUrl=Replace(Replace(RURI,"{0}",Server.URLEncode(Opt)),"{1}",Server.URLEncode(str))
Rs=getHTTPPage(newUrl)
GetText = AnalyzeChild("(<div id=result_box dir=""ltr"">)([?:\s\S]*?)(</div>)",Rs,1)
End Function
Sub class_Terminate
End Sub
End Class

然後使用的時候: 複製代碼 代碼如下:Dim Obj
Set Obj = new GoogleTranslator
Obj.Opt="zh-CN|en"
response.write(Obj.GetText("我們"))

然後就可以了,需要注意的是因為Google的任何產品都是UTF-8格式的,這個asp檔案儲存為UTF-8格式,並在開頭加上:
<%@ LANGUAGE=VBScript CodePage=65001%>
<%Option Explicit
'... 開抄我上面的代碼
就可以了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.