【问题标题】:urllib.urlencode: TypeError not a valid non-string sequence or mapping objecturllib.urlencode:TypeError 不是有效的非字符串序列或映射对象
【发布时间】:2016-04-29 02:30:05
【问题描述】:

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

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

【问题讨论】:

  • 欢迎来到stackoverflow!您应该在发布问题之前尝试使用搜索功能。关于这种类型的错误有很多答案可以帮助您解决问题并更快地前进。
  • 这能回答你的问题吗? cannot urllib.urlencode a URL in python

标签: python urllib


【解决方案1】:

urlencode 函数不接受单个字符串作为输入,它接受类似于字典的东西。

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

来自Documentation

urllib.urlencode(query[, doseq])

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2019-09-18
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多