首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从文本文件中获取多个坐标?

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

Stack Overflow用户
提问于 2019-07-09 16:50:03
回答 2查看 422关注 0票数 1

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

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

代码语言:javascript
复制
ABC;
 1 2
 6 -8;
DEF;
Coordinates
 3-5
 4 6
 9 7;
XYZ;
ABC;
Coordinates;
Coordinates
 1 2
 5 -1;

目前,我试图在字典中添加坐标,但只看到最后一个坐标。我尝试了一个while循环,如下:

代码语言:javascript
复制
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]]

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-07-09 17:09:49

您可以使用re来匹配regex.(doc)中的所有数字

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

代码如下:

代码语言:javascript
复制
# 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]}
票数 1
EN

Stack Overflow用户

发布于 2019-07-09 17:09:23

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

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56948723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档