You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从文本文件读取坐标点并判断是否在多边形内的技术求助

Fixing IndexError and Point-in-Polygon Check for Batch Coordinates

Let's break down the issues in your current script and walk through a corrected solution that handles your batch coordinate files properly.

1. Root Cause of the IndexError

Your script assumes each line in your text files holds exactly one (x,y) coordinate pair. But based on your description, both files likely have all coordinates in a single line (or contain empty lines). When you loop through lines and split them, empty lines result in an empty row list, leading to row[0] being out of range. Even if all coordinates are in one line, your code would only capture the first two values and fail on subsequent empty lines.

2. Incorrect Geometry Object Setup

  • You tried creating a single Point from lists of all x/y values—this doesn't work; Point expects a single (x,y) pair.
  • The Polygon was built incorrectly: it requires a list of (x,y) tuples, not two separate lists of x and y coordinates.

Corrected Script

Here's a revised script that fixes these issues and outputs control points inside the polygon:

from shapely.geometry import Point, Polygon

def read_coordinate_pairs(file_path):
    """Read all (x,y) pairs from a text file, handling any line structure."""
    coords = []
    with open(file_path, 'r') as file:
        for line in file:
            # Split line into individual values, ignoring extra whitespace/empty strings
            values = [val.strip() for val in line.split() if val.strip()]
            # Group values into (x,y) tuples and convert to floats
            for i in range(0, len(values), 2):
                if i + 1 < len(values):
                    x = float(values[i])
                    y = float(values[i+1])
                    coords.append((x, y))
    return coords

# Read and process polygon coordinates
polygon_coords = read_coordinate_pairs("polygon.txt")
polygon = Polygon(polygon_coords)

# Read and process control points
control_points = read_coordinate_pairs("controlPoints.txt")

# Check each control point and collect those inside the polygon
points_inside = []
for x, y in control_points:
    point = Point(x, y)
    if point.within(polygon):
        points_inside.append((x, y))

# Print the results
print("Control points inside the polygon:")
for coord in points_inside:
    print(f"{coord[0]:.3f} {coord[1]:.3f}")

Key Improvements Explained

  • Flexible Coordinate Reading: The read_coordinate_pairs function handles any line structure (all coords in one line, multiple lines, etc.). It skips empty lines and extra whitespace, then groups values into valid (x,y) pairs, eliminating the IndexError.
  • Correct Geometry Creation: The polygon is built from a list of (x,y) tuples, which is the required format for shapely.geometry.Polygon.
  • Batch Point Checking: We loop through each control point, create a Point object for each, and use point.within(polygon) to check if it lies inside the polygon.
  • Readable Output: Results are printed with 3 decimal places to match your input format.

How to Use

  1. Ensure polygon.txt contains all 24 numbers (12 vertices) in any line structure.
  2. Ensure controlPoints.txt contains all your control point coordinates (each pair as two numbers, in any line structure).
  3. Run the script—you'll see all control points inside the polygon printed to your terminal.

内容的提问来源于stack exchange,提问作者kwak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:34:41