【问题标题】:Fetching language detection from Google api从 Google api 获取语言检测
【发布时间】:2010-11-30 00:52:28
【问题描述】:

我有一个 CSV,其中一列包含关键字,第二列包含展示次数。

我想在 url 中提供关键字(循环时),并让 Google 语言 api 返回关键字所在的语言类型。

我让它手动工作。如果我输入(使用正确的 api 密钥): http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&key=myapikey&q=merde 我得到: {"responseData": {"language":"fr","isReliable":false,"confidence":6.213709E-4}, "responseDetails": null, "responseStatus": 200} 没错,“merde”是法语。

到目前为止,我有此代码,但我不断收到服务器无法访问的错误:

import time
import csv
from operator import itemgetter
import sys
import fileinput
import urllib2
import json

E_OPERATION_ERROR = 1
E_INVALID_PARAMS = 2

#not working
def parse_result(result):
  """Parse a JSONP result string and return a list of terms"""

  # Deserialize JSON to Python objects
  result_object = json.loads(result)

  #Get the rows in the table, then get the second column's value
  # for each row
  return row in result_object

#not working
def retrieve_terms(seedterm):

  print(seedterm) 
  """Retrieves and parses data and returns a list of terms"""
  url_template = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&key=myapikey&q=%(seed)s'
  url = url_template % {"seed": seedterm}


  try:
    with urllib2.urlopen(url) as data:
      data = perform_request(seedterm)
      result = data.read()
  except:
    sys.stderr.write('%s\n' % 'Could not request data from server')
    exit(E_OPERATION_ERROR)

  #terms = parse_result(result)
  #print terms
  print result

def main(argv):
  filename = argv[1]

  csvfile = open(filename, 'r')
  csvreader = csv.DictReader(csvfile)

  rows = []
  for row in csvreader:
    rows.append(row)

  sortedrows = sorted(rows, key=itemgetter('impressions'), reverse = True)

  keys = sortedrows[0].keys()

  for item in sortedrows:
    retrieve_terms(item['keywords'])

  try:
    outputfile = open('Output_%s.csv' % (filename),'w')
  except IOError:
    print("The file is active in another program - close it first!")
    sys.exit()  
  dict_writer = csv.DictWriter(outputfile, keys, lineterminator='\n')
  dict_writer.writer.writerow(keys)
  dict_writer.writerows(sortedrows)
  outputfile.close()

  print("File is Done!! Check your folder") 

if __name__ == '__main__':
  start_time = time.clock()
  main(sys.argv)
  print("\n")
  print time.clock() - start_time, "seconds for script time"

知道如何完成代码以使其正常工作吗?谢谢!

【问题讨论】:

    标签: python api


    【解决方案1】:

    尝试添加referreruserip,如the docs中所述:

    需要特别注意的地方 涉及正确识别 你自己在你的要求。 应用程序必须始终包含 有效且准确的 http referer 标头 在他们的要求中。此外,我们 要求,但不要求,每个 请求包含有效的 API 密钥。经过 提供密钥,您的应用程序 为我们提供了一个辅助 识别机制是 如果我们需要与您联系,这很有用 为了纠正任何问题。读 更多关于拥有一个 API 密钥

    开发人员也鼓励制作 userip 参数的使用(参见 下面)提供的IP地址 您代表的最终用户 发出 API 请求。这样做会 帮助区分这个合法的 服务器端流量来自流量 并非来自最终用户。

    这是一个基于the answer对问题"access to google with python"的示例:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import json
    import urllib, urllib2
    from pprint import pprint
    
    api_key, userip = None, None
    query = {'q' : 'матрёшка'}
    referrer = "https://stackoverflow.com/q/4309599/4279"
    
    if userip:
        query.update(userip=userip)
    if api_key:
        query.update(key=api_key)
    
    url = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&%s' %(
        urllib.urlencode(query))
    
    request = urllib2.Request(url, headers=dict(Referer=referrer))
    json_data = json.load(urllib2.urlopen(request))
    
    pprint(json_data['responseData'])
    

    输出

    {u'confidence': 0.070496580000000003, u'isReliable': False, u'language': u'ru'}
    

    另一个问题可能是 seedterm 没有被正确引用:

    if isinstance(seedterm, unicode):
       value = seedterm
    else: # bytes
       value = seedterm.decode(put_encoding_here)
    url = 'http://...q=%s' % urllib.quote_plus(value.encode('utf-8'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2015-08-15
      • 1970-01-01
      • 2019-07-16
      • 2011-12-30
      • 1970-01-01
      相关资源
      最近更新 更多