我正在设置一个脚本,我需要从一个文本文件中获取一些坐标。
我的文本文件的体系结构是:
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]]
发布于 2019-07-09 17:09:49
您可以使用re来匹配regex.(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]}发布于 2019-07-09 17:09:23
我不完全确定我是否理解了您的问题,但我认为这段代码可以完成工作:
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 = Falsehttps://stackoverflow.com/questions/56948723
复制相似问题