特定于语言的重定向

时间:2010-10-26 09:29:44

标签: python google-app-engine

我想创建一个简单的应用程序来检测短语的语言(使用Google API)并将其发送到相应的搜索引擎。例如,如果搜索查询是俄语,那么我需要在所有其他情况下将其重定向到Yandex.ru。

我就是这样做的:

def get(self):                                                                        
   decoded = unicode(unquote(self.request.query), "windows-1251")
   text = decoded.encode("utf-8")            
   url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+ quote(text)

   try:
      data = json.loads(urllib2.urlopen(url).read())                                
      redirectUrl = "http://www.google.com/search?q=" + text                        
      if data["responseData"]["language"] == 'ru':
          redirectUrl = "http://yandex.ru/yandsearch?text=" + text          
      self.redirect(redirectUrl)                                                           
    except urllib2.HTTPError, e:
      self.response.out.write( "HTTP error: %d" % e.code )
    except urllib2.URLError, e:
      self.response.out.write( "Network error: %s" % e.reason.args[1])

当我请求此网址“http://findinrightplace.appspot.com/q?test查询”时,它会重定向到谷歌但重定向到yandex不起作用(http://findinrightplace.appspot.com/q?тестовый запрос)。

我做错了什么?

4 个答案:

答案 0 :(得分:1)

您需要从url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+ quote(text)中移除quote(),它会为您的俄语查询返回错误的结果。

我在我的本地python shell中测试了你的代码,它没有使用quote(),但是没有使用quote()。

答案 1 :(得分:0)

我建议使用Google Prediction API [http://code.google.com/apis/predict/]。您会注意到主页上的示例正是您要执行的操作。

答案 2 :(得分:0)

在构建text时,您没有引用redirectUrl。尝试:

  ...
  redirectUrl = "http://www.google.com/search?q=" + quote(text)
  if data["responseData"]["language"] == 'ru':
      redirectUrl = "http://yandex.ru/yandsearch?text=" + quote(text)
  ...

答案 3 :(得分:0)

假设查询字符串是windows-1251编码,则表示错误。在您提供的链接中,由Web浏览器决定如何对其进行编码(因为HTTP对于URL的编码应该是静默的)。但是,今天,大多数浏览器都会假设URL必须以UTF-8编码。因为语言/检测还假设查询字符串是UTF-8编码的(并且URL转义),您既不需要取消引用也不需要解码字符串。此外,yandex支持UTF-8编码的查询字符串。所以把这一切放在一起:试试

def get(self):                                                                        
   text = self.request.query
   url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=" + text

   try:
      data = json.loads(urllib2.urlopen(url).read())                                
      redirectUrl = "http://www.google.com/search?q=" + text                        
      if data["responseData"]["language"] == 'ru':
          redirectUrl = "http://yandex.ru/yandsearch?text=" + text          
      self.redirect(redirectUrl)                                                           
    except urllib2.HTTPError, e:
      self.response.out.write( "HTTP error: %d" % e.code )
    except urllib2.URLError, e:
      self.response.out.write( "Network error: %s" % e.reason.args[1])