将多节文本文件读入多个数组

2024-09-27 17:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个多节文本文件,基本上是数千个数据集合,格式如下:

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(Generic Mapping Tools),其中每个部分在文件image.ps中绘制为彩色多边形,颜色由-G标记中的RGB值给定。每个部分以一个eof和一个标签(# 1)结束。你知道吗

基本上,我希望能够有两个独立的数组,一个用于从-G标记分割的单个RGB值,另一个用于每个单独的多边形顶点集。最终目标是使用各种matplotlib/basemap工具绘制这些多边形(不使用GMT)。你知道吗

这可能吗?我在其他帖子中看到它是possible for simpler formatting,但我对Python有些陌生。你知道吗

谢谢你。你知道吗


Tags: 数据标记image实用程序格式绘制rgb多边形
1条回答
网友
1楼 · 发布于 2024-09-27 17:34:11

我会这样做:

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])

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

相关问题 更多 >

    热门问题