【问题标题】:Get the last coordinates list from a text file从文本文件中获取最后一个坐标列表
【发布时间】:2017-12-25 01:04:21
【问题描述】:

我正在读取节点的坐标(76 个节点)。基本上我拆分了所有坐标的字符串。拆分后,我得到了节点坐标的结果,第一个数字是节点的数量,相应的坐标(x,y)。示例:

['1', '3600', '2300']

我只想获取从 61 到结束节点的节点坐标。我尝试通过将节点数转换为整数来进行比较。我不想删除 "while line != "EOF" 行,因为它显示在文本文件的末尾。我该怎么做?

 def read_coordinates(self, inputfile):
    coord = []
    iFile = open(inputfile, "r")
    for i in range(6):  # skip first 6 lines
        iFile.readline()
    line = iFile.readline().strip()
    while line != "EOF":
        values = line.split()
        while int(values[0]) > 61:
            coord.append([float(values[1]), float(values[2])])
            line = iFile.readline().strip()
    iFile.close()
    return coord

【问题讨论】:

  • 你有什么问题?
  • 代替while ... > 61,试试if ...
  • 哦,不,它不起作用。当我打印 int(values[0]) 时,它会给出值为 1 的无限循环。有什么建议吗?

标签: python coordinate


【解决方案1】:

您应该在while line != "EOF": 中使用 if 语句,如下所示:

while line != "EOF":
    values = line.split()
    if int(values[0]) > 61:
        coord.append([float(values[1]), float(values[2])])
    line = iFile.readline().strip()

另一种解决方案是读取孔文件,然后使用列表切片删除前 6 行并使用列表解析删除大于 61 的节点。

  with open(iFile, 'r') as f:
      coords = [ line.split(' ') for line in f]  # Read every line
      coords = coords[6:]  # Skip first 6 lines
      coords = [ [x,y] for nr, x, y in coords if int(nr) > 61] # Remove every node large    r than after 61

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2018-06-27
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    相关资源
    最近更新 更多