urllib.urlencode:TypeError不是有效的非字符串序列或映射对象

时间:2016-01-22 13:12:54

标签: python urllib

我正在尝试运行以下代码,但它给出了以下错误:

Traceback (most recent call last):  File "put_message.py", line 43, in <module>translatedWord=getTranslatedValue(source_lang,source_word,dest_lang,apiKey)  File "put_message.py", line 22, in getTranslatedValue
    source_word=urllib.urlencode(source_word)
  File "/usr/lib/python2.7/urllib.py", line 1318, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object

我的计划如下:

将数据从一种语言翻译成另一种语言的脚本

import MySQLdb
import json
import urllib, urllib2
import requests
from pprint import pprint
import sys


def getTranslatedValue(source_lang,source_word,dest_lang,apiKey):


    source_word=urllib.urlencode(source_word)   
    url='https://www.googleapis.com/language/translate/v2?key=%s&q=%s&source=%s&target=%s',(apiKey,source_word,source_lang,dest_lang)
    j = urllib2.urlopen(url)
    j_obj = json.load(j)
    j.close()
    translatedText=j_obj['data']['translations'][0]['translatedText']
    return translatedText


# Open database connection
db = MySQLdb.connect(host,user,password)

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
getCategory = " SELECT entity_id,attribute_id,VALUE FROM magento19_org.catalog_category_entity_text WHERE attribute_id IN(44,47,48)  UNION ALL SELECT entity_id,attribute_id,VALUE FROM magento19_org.catalog_category_entity_varchar WHERE attribute_id IN(41,46)"
cursor.execute(getCategory)
rows = cursor.fetchall()
for row in rows:
                 source_word=row[2]
                 translatedWord=getTranslatedValue(source_lang,source_word,dest_lang,apiKey)
                 entity_id=row[0]
                 attribute_id=row[1]
                 value=row[2]
                 insertCategoryTranslate="insert into googletranslate.category_translate(entity_id ,attribute_id ,value,french_translate )values(%s,%s,%s,%s)"
                 cursor.execute(insertCategoryTranslate,(str(entity_id),str(attribute_id),str(value),str(translatedWord)))
                 db.commit()
# disconnect from server
db.close()

1 个答案:

答案 0 :(得分:8)

urlencode函数不会将单个字符串作为输入,它需要类似字典的内容。

data = urlencode({'key': apiKey, 'q': source_word, ...)
urllib2.urlopen("http://....", data)

来自Documentation

  

<强> urllib.urlencode(query[, doseq])

     

将映射对象或两元素元组序列转换为“百分比编码”字符串,适合传递给上面的urlopen()作为可选数据参数。这对于将表单字段的字典传递给POST请求很有用。结果字符串是由'&amp;'分隔的一系列键=值对字符,其中键和值都使用上面的quote_plus()引用。当一个两元素元组序列用作查询参数时,每个元组的第一个元素是一个键,第二个元素是一个值。