如何从文本文件中获取多个坐标?

时间:2019-07-09 08:50:03

标签: python dictionary

我正在设置脚本,我需要从文本文件中获取一些坐标。

我的文本文件的体系结构是:

ABC;
 1 2
 6 -8;
DEF;
Coordinates
 3-5
 4 6
 9 7;
XYZ;
ABC;
Coordinates;
Coordinates
 1 2
 5 -1;

目前,我尝试将坐标添加到字典中,但只能看到最后一个坐标。我已经尝试过使用while循环:

file = open(txt, 'r')
line = file.readline()
while line:
   if line.lstrip().startswith('Coordinates') and not (line.rstrip().endswith(';')):
       coordinates['points'].append((x, y))

我已经定义了我的X和Y点,但是我没有找到将每个坐标添加到字典中的方法。

预期输出: ['points':[3, -5, 4, 6, 9, 7, 1, 2, 5, -1]]

但暂时,这是我的输出:['points':[1, 2, 5, -1]]

2 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解您的问题,但是我认为这段代码可以完成工作:

with open(txt, "r") as f:
    lines = f.readlines()
output = {"points": []}
next_line_has_coords = False
for line in lines:
    text = line.strip()
    if next_line_has_coords:
        list_numbers = text.replace("-", " -").replace(";", "").split(" ")
        output["points"] += [int(number) for number in list_numbers if number != ""]
    if text.startswith("Coordinates") and not text.endswith(";"):
        next_line_has_coords = True
    if text.endswith(";"):
        next_line_has_coords = False

答案 1 :(得分:1)

您可以使用re匹配正则表达式中的所有数字。(doc)

我还使用map将每个数字转换为float类型。 (help on map)

代码在这里:

# import module
import re
# Create output variable
res = {"Points": []}

# Read file
with open("temp.txt", "r") as f:
    # Read line
    line = f.readline()
    while line:
        # Find begining block
        if "Coordinates" in line:
            # Read block
            while line and "Coordinates;" not in line:
                # Match numbers on line (with the - if negative)
                numbers = re.findall(r'(\-{0,1}\d+)', line)
                # If there are number
                if len(numbers) > 0:
                    # Add them as float
                    res["Points"] += map(float, numbers)
                    # Read next line
                line = f.readline()
        # Read next line
        line = f.readline()

print(res)
# {'Points': [3.0, -5.0, 4.0, 6.0, 9.0, 7.0, 1.0, 2.0, 5.0, -1.0]}