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

如何在Python中正确捕获文本文件中坐标重复的行?

解决坐标组合重复行提取问题

你的问题核心在于没有把纬度和经度作为一个完整的组合来判断重复,而是单独检查每个值是否存在,这就导致只要其中一个值重复就会被误判。咱们来修正这个逻辑,核心思路是把(latitude, longitude)作为一个不可变的元组,统计这个组合的出现次数,再把出现次数≥2的行提取出来。

错误原因分析

你修改后的代码中,把columns[3](纬度)和columns[4](经度)分别加入entries列表,判断时也是单独检查某一个值是否在列表里。比如当两行的经度相同但纬度不同时,经度值已经在entries里,就会被误判为重复,这完全不符合你要的「坐标组合完全重复」的需求。

修正后的代码

from collections import defaultdict

# 第一步:统计每个坐标组合的出现次数
coordinate_counts = defaultdict(int)
input_file = '/home/usr/python-programming/ip-infos'

with open(input_file, 'r') as arq:
    for line in arq:
        # 分割每行数据为列
        columns = line.strip().split(',')
        # 避免因数据格式错误导致索引越界
        if len(columns) >= 5:
            # 将纬度+经度组合成元组作为统计键
            coord = (columns[3], columns[4])
            coordinate_counts[coord] += 1

# 第二步:提取所有坐标组合重复的行
output_file = '/home/usr/python-programming/suspects'
with open(output_file, 'w') as out_file:
    with open(input_file, 'r') as arq:
        for line in arq:
            columns = line.strip().split(',')
            if len(columns) >= 5:
                coord = (columns[3], columns[4])
                # 仅保留出现次数大于1的行
                if coordinate_counts[coord] > 1:
                    out_file.write(line)
                    print(line.strip())

# 反馈结果
if any(count > 1 for count in coordinate_counts.values()):
    print(f"已提取重复坐标的行到 {output_file}")
else:
    print("没有找到重复的坐标组合")

代码说明

  • 使用collections.defaultdict统计次数,比手动维护列表更高效,尤其适合处理数千条数据的场景。
  • 把(latitude, longitude)作为元组(不可变类型,可作为字典键),确保只有当两个值完全相同时才被判定为重复。
  • 增加列数检查,避免因部分行数据格式错误导致的程序崩溃。
  • 分两次遍历文件:第一次统计次数,第二次提取目标行,逻辑清晰且性能稳定。

如果不想导入defaultdict,也可以用普通字典实现统计逻辑:

coordinate_counts = {}
with open(input_file, 'r') as arq:
    for line in arq:
        columns = line.strip().split(',')
        if len(columns) >= 5:
            coord = (columns[3], columns[4])
            coordinate_counts[coord] = coordinate_counts.get(coord, 0) + 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:36:27