欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP Google的translate API代码

程序员文章站 2023-01-24 23:28:11
直接看代码: 复制代码 代码如下:class googletranslator sub class_initialize() ruri="http://translate....
直接看代码:
复制代码 代码如下:

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
'... 开抄我上面的代码
就可以了。