lin用分隔符行分析文本

2024-04-23 10:48:18 发布

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

有人能告诉我你怎么用python处理这个问题吗? 我试图解析一个包含坐标列表的文本文件

XCOORDINATE|YCOORDINATE
XCOORDINATE|YCOORDINATE
XCOORDINATE|YCOORDINATE
...

我试着解析第1行的坐标,然后在第2行做同样的事情,等等。 我很难将每一行划分为“XCOORDINATE”和“YCOORDINATE”,解析它,然后转到下一行。在

感谢您抽出时间!在


Tags: 列表时间事情文本文件ycoordinatexcoordinate
1条回答
网友
1楼 · 发布于 2024-04-23 10:48:18

您只需迭代文件,并使用str.split()将字符串划分为两个单独的坐标:

with open('full/path/to/file.txt') as file:
    for line in file:
        # Filter out any whitespace
        line = line.replace(' ', '').strip()

        # Split each line into a list containing two parts. The x coordinate
        # and the y coordinate. Unpack the list into two variables.
        xcoord, ycoord = line.split('|')

        # Use the coordinates here
        print(xcoord)
        print(ycoord)

您可能还需要将两个坐标转换为整数,在这种情况下,可以执行以下操作:

^{pr2}$

相关问题 更多 >