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

2024-05-23 17:43:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图运行以下代码,但出现以下错误:

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()

Tags: inimportidsourcelangdbattributeurllib
1条回答
网友
1楼 · 发布于 2024-05-23 17:43:51

urlencode函数不接受单个字符串作为输入,而是接受类似字典的内容。

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

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.

相关问题 更多 >