返回AttributeError:'int'对象没有属性'encode'

时间:2015-10-02 03:50:05

标签: python json encoding elasticsearch

我遇到了一些问题,我一直在说:

AttributeError: 'int' object has no attribute 'encode'

当我跑的时候。

我认为UTF-8就是这样的。订阅者只会返回数字或NoneTypes。

非常感谢任何帮助。

import urllib2,time,csv,json,requests,urlparse,pdb



SEARCH_URL = urllib2.unquote("http://soyuz.elastic.tubularlabs.net:9200/intelligence_v2/channel_intelligence/%s")

reader = csv.reader(open('input.csv', 'r+U'), delimiter=',', quoting=csv.QUOTE_NONE)
#cookie = {"user": "2|1:0|10:1438908462|4:user|36:eyJhaWQiOiA1Njk3LCAiaWQiOiA2MzQ0fQ==|b5c4b3adbd96e54833bf8656625aedaf715d4905f39373b860c4b4bc98655e9e"}

myfile = open('accounts.csv','w')

writer = csv.writer(myfile, quoting=csv.QUOTE_MINIMAL)

processCount = 1
idsToProcess = []
for row in reader:
    if len(row)>0:
        idsToProcess.append(row[0])
#idsToProcess = ['fba_491452930867938']
for userID in idsToProcess:
#   print "fetching for %s.." % fbid
    url = SEARCH_URL % userID
    facebooksubscribers = None
    Instagramsubscribers = None
    vinesubscribers = None

    response = requests.request("GET", url)
    ret = response.json()
    titleResponse = ret['_source']['title']

    try:
        facebooksubscribers = ret['_source']['facebook']['subscribers']          
    except:
        facebooksubscribers = " "

    try:
        instagramsubscribers = ret['_source']['instagram']['subscribers']
    except:
        instagramsubscribers = " "

    try:
        vinesubscribers = ret['_source']['vine']['subscribers']
    except:
        vinesubscribers = " "



    time.sleep(0)

    row = [s.encode('utf-8') for s in [userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]]
    writer.writerow(row)

    #writer.writerow([userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers,twitterURL])

    myfile.flush()

    print u"%s,%s,%s,%s,%s,%s" % (processCount,userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers)
    processCount += 1
    #print sumEngs

    #print vidToEngs
    #print sum(vidToEngs.values())
myfile.close()
exit()

3 个答案:

答案 0 :(得分:5)

因为其中一个

[userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]‌

元素是int,你不能对int执行编码操作。您可能希望在for循环中进行类型转换。替换

row = [s.encode('utf-8') for s in [userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]]‌​

row = [str(s).encode('utf-8') for s in [userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]]‌

答案 1 :(得分:1)

使用此:

repr(s).encode('utf-8')

而不是:

s.encode('utf-8')

答案 2 :(得分:0)

从xlsx文件加载数据时,我遇到了类似的问题。实施上述解决方案后,我遇到的问题是我将收到错误:

AttributeError: 'int' object has no attribute 'encode'

因为我解析的数据不只是unicode。我发现的解决方案是一个简单的try / except,如果抛出错误,我只会使用.encode('utf-8')。这是代码:

    try:
        s2 = str(foo)
    except:
        s2 = foo.encode('utf-8').strip()

我不知道这是一次性的事情,还是其他人可能遇到此问题。希望对您有所帮助。