2

我编写了这个函数来读取Las文件并保存一个 shapefile。该函数创建一个包含 8 个字段的 shapefile。我希望在函数中插入一个解析元素以选择我希望保存的字段 LAS2SHP(inFile,outFile=None,parse=None)。如果 None 保存所有字段。如果parse为 parse="irn",则保存场强度、return_number 和 number_of_returns。跟随传说

"i": p.intensity,
"r": p.return_number,
"n": p.number_of_returns,
"s": p.scan_direction,
"e": p.flightline_edge,
"c": p.classification,
"a": p.scan_angle, 

我写了一个解决方案 if....ifelse....else 真的很消耗代码(而不是优雅)。感谢所有关于保存代码的帮助和建议

提前感谢詹尼

这里是python中的原始函数

import shapefile
from liblas import file as lasfile

def LAS2SHP(inFile,outFile=None):
    w = shapefile.Writer(shapefile.POINT)
    w.field('Z','C','10')
    w.field('Intensity','C','10')
    w.field('Return','C','10')
    w.field('NumberRet','C','10')
    w.field('ScanDir','C','10')
    w.field('FlightEdge','C','10')
    w.field('Class','C','10')
    w.field('ScanAngle','C','10')
    for p in lasfile.File(inFile,None,'r'):
        w.point(p.x,p.y)
        w.record(float(p.z),float(p.intensity),float(p.return_number),float(p.number_of_returns),float(p.scan_direction),float(p.flightline_edge),float(p.classification),float(p.scan_angle))
    if outFile == None:
        inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))
        inFile_name = os.path.splitext(inFile_name_ext)[0]
        w.save("{0}\\{1}.shp".format(inFile_path,inFile_name))
    else:
        w.save(outFile)
4

1 回答 1

1

也许尝试这样的事情:

    pdata = [p.z] + [getattr(p, pattr[key]) for key in parse]
    pdata = map(float, pdata)
    w.record(*pdata)
  • for key in parse循环遍历parse. 例如, if parse = 'irn'then key 循环遍历值i, r, n
  • pattr是一个字典。pattr[key]是关联属性的名称。例如,pattr['i']"intensity"
  • getattr(p, pattr[key])是 中的pattr[key]属性值p。例如,getattr(p, "intensity")p.intensity。当您知道属性名称为字符串(例如pattr[key])时,这是获取属性值的方法。*in在将参数发送到 之前w.record(*pdata)解包。例如,等价于。这是向函数发送任意数量的参数的方式。pdataw.recordw.record(*[1,2,3])w.record(1,2,3)

例如,

import shapefile
from liblas import file as lasfile

pattr = {
    "i": 'intensity',
    "r": 'return_number',
    "n": 'number_of_returns',
    "s": 'scan_direction',
    "e": 'flightline_edge',
    "c": 'classification',
    "a": 'scan_angle',
    }

wattr = {
    "i": 'Intensity',
    "r": 'Return',
    "n": 'NumberRet',
    "s": 'ScanDir',
    "e": 'FlightEdge',
    "c": 'Class',
    "a": 'ScanAngle',
    }

def LAS2SHP(inFile, outFile=None, parse = 'irnseca'):
    w = shapefile.Writer(shapefile.POINT)
    w.field('Z','C','10')
    for key in parse:
        w.field(wattr[key],'C','10')
    for p in lasfile.File(inFile,None,'r'):
        w.point(p.x,p.y)
        pdata = [p.z] + [getattr(p, pattr[key]) for key in parse]
        pdata = map(float, pdata)
        w.record(*pdata)       
    if outFile == None:
        inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))
        inFile_name = os.path.splitext(inFile_name_ext)[0]
        w.save("{0}\\{1}.shp".format(inFile_path,inFile_name))
    else:
        w.save(outFile)
于 2012-10-25T17:21:52.103 回答