-4

我正在尝试创建一个新字典,其中将列出树的物种以及该物种的 DBH。每个物种将有多个 DBH。它从文本文件中提取此信息。

创建第一个字典的部分正在工作(列出每个物种的物种和数量),但我无法让它为每个物种附加 DBH。我继续收到错误 AttributeError: 'float' object has no attribute 'append'。我已经搜索和搜索并尝试了多种方法,但无法使其正常工作。

import string, os.path, os, sys


filepath = "C:\\temp\\rdu_forest1.txt"
data=[]
#Open the text file
myfile=open(filepath,'r')
#Read the text file
myfile.readline() #read the field name line
row = myfile.readline()
count = 0
while row:
    myline = row.split('\t') #Creat a list of the values in this row.  Columns are tab separated.
    #Reads a file with columns: Block Plot  Species DBH MerchHeight
    data.append([float(myline[0]),float(myline[1]),myline[2].rstrip(),float(myline[3].rstrip())]) 
    #rstrip removes white space from the right side
    count = count + 1
    row = myfile.readline()
myfile.close()
mydict={}

mydict2={} #Create an emyty mydict2 here  *********

for row in data:  # for each row
    # create or update a dictionary entry with the current count for that species
    species = row[2]#Species is the third entry in the file
    DBH = row[3] #DBH is the fourth entry in the file 
    if mydict.has_key(species):  #if a dictionary entry already exists for this species
        #Update dict for this species
        cur_entry = mydict[species]
        cur_entry = int(cur_entry)+1
        mydict[species] = cur_entry

        #update mydict2 here  *********
        mydict2[species].append(DBH)

    else:#This is the first dictionary entry for this species
        #Create new dict entry with sums and count for this species
        mydict[species]=1
        mydict2[species]=DBH #Add a new entry to mydict2 here  *********

print mydict

这是追溯

Traceback (most recent call last):
  File "C:\Python27\ArcGIS10.1\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec codeObject in __main__.__dict__
  File "E:\Python\16\dictionary.py", line 40, in <module>
    mydict2[species].append(DBH)
AttributeError: 'float' object has no attribute 'append'
4

1 回答 1

4

对我来说看起来很简单。

mydict2[species].append(DBH)

在这里初始化:

mydict2[species]=DBH

来自这里:

DBH = row[3]

来自这里:

data.append([float(myline[0]),float(myline[1]),myline[2].rstrip(),float(myline[3].rstrip())]) 

所以它是一个浮动。而且你不能附加到一个浮点数,所以你会得到那个错误。

我认为您可能打算列出这些 DBH:

mydict2[species] = [DBH]

或者,您可以查看defaultdict

from collections import defaultdict
mydict2 = defaultdict(list)
mydict2[species].append(DBH)

并且您可以删除if-stmt-- 如果没有,则代码会列出一个列表并始终附加。

而且我还会考虑使用csv库来处理您的制表符分隔文件。


这是我想象的你会将代码更改为:

import csv
from collections import defaultdict

def read_my_data(filepath="C:\\temp\\rdu_forest1.txt"):
    with open(filepath, 'r') as myfile:
        reader = csv.reader(myfile, delimiter='\t')
        return [
            [float(myline[0]),float(myline[1]),myline[2].rstrip(),float(myline[3].rstrip())]
            for row in reader
        ]

mydict2 = defaultdict(list)

for _, _, species, DBH  in read_my_data():
    mydict2[species].append(DBH)

mydict = {
    k: len(v)
    for k, v in mydict2.iteritems()
}

print mydict

并不是说我实际上已经运行过这个或任何东西。如果您仍然遇到问题,请告诉我defaultdict

于 2013-10-26T18:58:21.820 回答