【问题标题】:Python, AttributeError: 'float' object has no attribute 'encode'Python,AttributeError:'float'对象没有属性'encode'
【发布时间】:2015-03-28 04:47:48
【问题描述】:

我有一个使用总线位置 API 的脚本,我正在尝试解析作为浮点对象的 lat/lng 字段。我反复收到此错误。

row.append(十进制(items['longitude'].encode('utf-16'))) AttributeError: 'float' 对象没有属性 'encode'

# IMPORTS
from decimal import *

#Make Python understand how to read things on the Internet
import urllib2

#Make Python understand the stuff in a page on the Internet is JSON
import simplejson as json
from decimal import Decimal

# Make Python understand csvs
import csv

# Make Python know how to take a break so we don't hammer API and exceed rate limit
from time import sleep

# tell computer where to put CSV
outfile_path='C:\Users\Geoffrey\Desktop\pycharm1.csv'

# open it up, the w means we will write to it
writer = csv.writer(open(outfile_path, 'wb'))

#create a list with headings for our columns
headers = ['latitude', 'longitude']

#write the row of headings to our CSV file
writer.writerow(headers)


# GET JSON AND PARSE IT INTO DICTIONARY

# We need a loop because we have to do this for every JSON file we grab

#set a counter telling us how many times we've gone through the loop, this is the first time, so we'll set it at 1
i=1

#loop through pages of JSON returned, 100 is an arbitrary number
while i<100:
    #print out what number loop we are on, which will make it easier to track down problems when they appear
    print i
    #create the URL of the JSON file we want. We search for 'egypt', want English tweets, 
#and set the number of tweets per JSON file to the max of 100, so we have to do as little looping as possible
    url = urllib2.Request('http://api.metro.net/agencies/lametro/vehicles' + str(i))
    #use the JSON library to turn this file into a Pythonic data structure
    parsed_json = json.load(urllib2.urlopen('http://api.metro.net/agencies/lametro/vehicles'))
    #now you have a giant dictionary.
#Type in parsed_json here to get a better look at this. 
#You'll see the bulk of the content is contained inside the value that goes with the key, or label "results". 
#Refer to results as an index. Just like list[1] refers to the second item in a list, 
#dict['results'] refers to values associated with the key 'results'.
    print parsed_json



    #run through each item in results, and jump to an item in that dictionary, ex: the text of the tweet
    for items in parsed_json['items']:

     #initialize the row
         row = []
     #add every 'cell' to the row list, identifying the item just like an index in a list
#if latitude is not None:
    #latitude = str(latitude)
#if longitude is not None:
    #longitude = str(longitude)
    row.append(Decimal(items['longitude'].encode('utf-16')))
    row.append(Decimal(items['latitude'].encode('utf-16')))
     #row.append(bool(services['predictable'].unicode('utf-8')))
     #once you have all the cells in there, write the row to your csv
    writer.writerow(row)
    #increment our loop counter, now we're on the next time through the loop
    i = i +1
    #tell Python to rest for 5 secs, so we don't exceed our rate limit
    sleep(5)

【问题讨论】:

    标签: python json unicode encode


    【解决方案1】:

    encode 是字符串具有的方法,而不是浮点数。

    row.append(Decimal(items['longitude'].encode('utf-16'))) 更改为row.append(Decimal(str(items['longitude']).encode('utf-16'))) 并与另一行类似。

    【讨论】:

      【解决方案2】:

      encode 仅适用于字符串。在您的情况下, item['longitude'] 是一个浮点数。 float 没有编码方法。您可以输入大小写,然后使用编码。 你可以这样写,

      str(items['longitude']).encode('utf-16')
      str(items['latitude']).encode('utf-16')
      

      我认为您不能将编码字符串传递给 Decimal 对象。

      【讨论】:

      • 运行,但不写入 CSV,也没有记录错误。
      • 它是如何工作的?如果您已对其进行编码,它将抛出 decimal.InvalidOperation 消息 Invalid literal for string
      猜你喜欢
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2018-10-02
      • 2013-11-05
      • 2020-07-13
      相关资源
      最近更新 更多