zl程序教程

您现在的位置是:首页 >  其他

当前栏目

ASPGoogle的translateAPI代码

2023-06-13 09:14:07 时间
直接看代码:
复制代码代码如下:

ClassGoogleTranslator
subClass_Initialize()
RURI="http://translate.google.com/translate_t?langpair={0}&text={1}"
EndSub
PrivateOpt_"
PropertyGetOpt
Opt=Opt_
EndProperty
PropertyLetOpt(Opt_s)
Opt_=Opt_s
EndProperty
PrivateRURI
FunctionAnalyzeChild(patrn,texts,IPos)
DimregEx,Match,Matches
SetregEx=NewRegExp
regEx.IgnoreCase=true
regEx.Global=True
regEx.Pattern=patrn
regEx.Multiline=True
DimRetStr
SetMatches=regEx.Execute(texts)
If(Matches.Count>0)ThenRetStr=Matches(0).SubMatches(IPos)
AnalyzeChild=RetStr
SetregEx=Nothing
EndFunction
FunctiongetHTTPPage(url)
dimobjXML
setobjXML=server.createobject("MSXML2.XMLHTTP")"定义
objXML.open"GET",url,false"打开
objXML.send()"发送
IfobjXML.readystate<>4then
exitfunction
EndIf
getHTTPPage=BytesToBstr(objXML.responseBody)
setobjXML=nothing"关闭
iferr.number<>0thenerr.Clear
EndFunction
FunctionBytesToBstr(body)
dimobjstream
setobjstream=Server.CreateObject("adodb.stream")
objstream.Type=1
objstream.Mode=3
objstream.Open
objstream.Writebody
objstream.Position=0
objstream.Type=2
objstream.Charset="utf-8"
"转换原来默认的UTF-8编码转换成GB2312编码,否则直接用XMLHTTP调用有中文字符的网页得到的将是乱码
BytesToBstr=objstream.ReadText
objstream.Close
setobjstream=nothing
EndFunction
PublicFunctionGetText(str)
If(isempty(str))ThenExitFunction
DimnewUrl,Rs
newUrl=Replace(Replace(RURI,"{0}",Server.URLEncode(Opt)),"{1}",Server.URLEncode(str))
Rs=getHTTPPage(newUrl)
GetText=AnalyzeChild("(<divid=result_boxdir=""ltr"">)([?:\s\S]*?)(</div>)",Rs,1)
EndFunction
Subclass_Terminate
EndSub
EndClass


然后使用的时候:
复制代码代码如下:

DimObj
SetObj=newGoogleTranslator
Obj.Opt="zh-CN|en"
response.write(Obj.GetText("我们"))

然后就可以了,需要注意的是因为Google的任何产品都是UTF-8格式的,这个asp文件保存为UTF-8格式,并在开头加上:
<%@LANGUAGE=VBScriptCodePage=65001%>
<%OptionExplicit
"...开抄我上面的代码
就可以了。