写入 Shapefile

Writing to a Shapefile

我在 python 中遇到 writing/reading Shapefile 问题。我有一组点,我想使用 pyshp 将它们写入多边形。代码的相关部分是:

dividedRects = [(7598325.0, 731579.0, 7698325.0, 631579.0), (7598325.0, 631579.0, 7698325.0, 611641.0), (7698325.0, 731579.0, 7728636.0, 631579.0), (7698325.0, 631579.0, 7728636.0, 611641.0)]

def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
        w.field("ID", "C", "40")
        w.field("Events", "C", "40")
        w.record(str(i), str(0))
    w.save('cellFile')

createPolys(dividedRects)

这会导致错误:

IndexError                                Traceback (most recent call last)
<ipython-input-36-503affbe838b> in <module>()
----> 1 createPolys(dividedRects)

<ipython-input-35-4c552ae29bc7> in createPolys(dividedRects)
     10         w.field("ID", "C", "40")
     11         w.field("Events", "C", "40")
---> 12         w.record(str(i), str(0))
     13     w.save('cellFile')
     14 #     topLeft = [dividedRects[1][0],dividedRects[1][1]]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in record(self, *recordList, **recordDict)
    967         if self.fields[0][0].startswith("Deletion"): fieldCount -= 1
    968         if recordList:
--> 969             [record.append(recordList[i]) for i in range(fieldCount)]
    970         elif recordDict:
    971             for field in self.fields:

IndexError: tuple index out of range

如果我从 createPolys 中删除 fieldrecords 行:

def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
#         w.field("ID", "C", "40")
#         w.field("Events", "C", "40")
#         w.record(str(i), str(0))
    w.save('cellFile')

然后我在从文件中读取记录时得到一个断言错误:

createPolys(dividedRects)

sf2 = shapefile.Reader("cellFile")
print sf2.records()
shapes = sf2.shapes()
bbox = shapes[1].bbox
#['%.3f' % coord for coord in bbox]
print bbox
points = shapes[1].points
print points

AssertionError                            Traceback (most recent call last)
<ipython-input-37-597af0b882ba> in <module>()
      1 sf2 = shapefile.Reader("cellFile")
----> 2 print sf2.records()
      3 shapes = sf2.shapes()
      4 bbox = shapes[1].bbox
      5 #['%.3f' % coord for coord in bbox]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in records(self)
    528         """Returns all records in a dbf file."""
    529         if not self.numRecords:
--> 530             self.__dbfHeader()
    531         records = []
    532         f = self.__getFileObj(self.dbf)

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in __dbfHeader(self)
    464             self.fields.append(fieldDesc)
    465         terminator = dbf.read(1)
--> 466         assert terminator == b("\r")
    467         self.fields.insert(0, ('DeletionFlag', 'C', 1, 0))
    468 

AssertionError: 

当我移除循环并写入一条记录时,它似乎工作正常。怎么回事?

我不知道 pyshp 图书馆,但我会尽力提供帮助。

两个w.field()命令出现在for循环中。这可能会导致 "ID" 和 "Events" 这两列被定义多次。当你只写一条记录(多边形)时,它工作正常(即 w.record() 命令包含两个值)。第一次迭代后,将有 4、6 等列。这可以解释您描述的行为。

尝试将 w.field() 行移动到 for loop.

之前

当您注释 w.record() 时,您会获得一个 shp(和 shx)文件,其中的记录数与相应的 dbf 文件不同。这解释了阅读时的断言错误。

与您的问题无关,您还可以使用 enumerate(内置函数)简化代码。

w = shapefile.Writer(shapefile.POLYGON)
w.field("ID", "C", "40")
w.field("Events", "C", "40")    
for i,rect1 in enumerate(dividedRects):
    print i
    topLeft = [rect1[0],rect1[1]]
    topRight = [rect1[2], rect1[1]]
    bottomRight = [rect1[2], rect1[3]]
    bottomLeft = [rect1[0], rect1[3]]
    ....

(没有pyshp无法测试)祝你好运!