I am trying to run following code but it is giving me below error:
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
my program is given below:
Script to Translate the data from one language to another
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()
The urlencode
function does not take a single string as input, it takes a something like a dictionary.
data = urlencode({'key': apiKey, 'q': source_word, ...)
urllib2.urlopen("http://....", data)
From the Documentation,
urllib.urlencode(query[, doseq])
Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string, suitable to pass to urlopen() above as the optional data argument. This is useful to pass a dictionary of form fields to a POST request. The resulting string is a series of key=value pairs separated by '&' characters, where both key and value are quoted using quote_plus() above. When a sequence of two-element tuples is used as the query argument, the first element of each tuple is a key and the second is a value.
来源:https://stackoverflow.com/questions/34947568/urllib-urlencode-typeerror-not-a-valid-non-string-sequence-or-mapping-object