1

我有一个多节文本文件,它本质上是数千个具有以下格式的数据集合:

psxy -R -Jm -N -G0/19/255 -K -O <<eof>> image.ps
   64.0100  28.0100
   64.0400  28.0100
   64.0700  28.0100
   64.1000  28.0100
   64.1400  28.0100
   64.1700  28.0100
   64.2000  28.0100
   64.2300  28.0100
   64.2600  28.0100
   64.2600  28.0400
   64.2600  28.0700
   64.2600  28.1000
   64.2600  28.1400
   64.2600  28.1700
   64.2600  28.2000
   64.2600  28.2300
   64.2600  28.2600
   64.2300  28.2600
   64.2000  28.2600
   64.1700  28.2600
   64.1400  28.2600
   64.1000  28.2600
   64.0700  28.2600
   64.0400  28.2600
   64.0100  28.2600
   64.0100  28.2300
   64.0100  28.2000
   64.0100  28.1700
   64.0100  28.1400
   64.0100  28.1000
   64.0100  28.0700
   64.0100  28.0400
   64.0100  28.0100
eof
 #   1

第一行调用实用程序 GMT(通用映射工具),其中每个部分都在文件中绘制image.ps为彩色多边形,颜色由-G标记中的 RGB 值给出。每个部分都以一个eof和一个标签 ( # 1) 结尾。

基本上,我希望能够有两个单独的数组,一个用于从-G标签中拆分出来的单个 RGB 值,另一个用于每个单独的多边形顶点集。最终目标是使用各种 matplotlib/底图工具绘制这些多边形(不使用 GMT)。

这可能吗?我在其他帖子中看到可以进行更简单的格式化,但我对 Python 有点陌生。

谢谢你。

4

1 回答 1

1

我会做这样的事情:

import re

polygons = []

with open('inputfilename') as datafile:
    for line in datafile:

        if 'psxy' in line:
#This is the beginning of a new polygon. Start with an empty set of points
#and parse out the color, and store it in a tuple
            points = []
            m = re.search('-G([\d\.]+)/([\d\.]+)/([\d\.]+) ', line)
            r,g,b = m.group(1,2,3)
            r = int(r)
            g = int(g)
            b = int(b)
            color = (r,g,b)

        elif 'eof' in line:
#This is the end of a polygon. Take the list of points, and the last color
#put them in a tuple and append that to the list of polygons
            polygons.append((points, color))

        elif '#' in line:
#do nothing with this line
            pass

        else:
#This is a pair of x,y coordinates. Turn them into floats, put them in a tuple
#and append the tuple to the list of points for this polygon.
            x,y = line.split()
            x = float(x)
            y = float(y)
            points.append((x,y))


#Now to plot the polygons
for poly in polygons:
    drawPolygon(poly[0], poly[1])

这是一个非常简单的示例,没有错误检查。如果输入文件语法出现意外情况,它将中断。它也可能有错别字和其他错误。如果它坏了,你可以保留所有的碎片。:)

于 2013-11-05T21:14:51.587 回答