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

Python读取含Grid-ref前缀的文件数值并赋值给xref、yref变量的方法

提取文本文件中Grid-ref的数值

这里提供两种符合你需求的实现方法,任选其一即可:

方法一:通过行内容判断提取

直接遍历文件每一行,判断是否以Grid-ref=开头,符合条件就提取数值:

xref_list = []
yref_list = []

# 替换成你的文件路径
with open('your_file.txt', 'r') as f:
    for line in f:
        cleaned_line = line.strip()
        if cleaned_line.startswith('Grid-ref='):
            # 拆分前缀和数值部分
            num_section = cleaned_line.split('=', 1)[1].strip()
            # 拆分两个数值字符串并转为整数
            x_str, y_str = num_section.split(',')
            xref = int(x_str.strip())
            yref = int(y_str.strip())
            
            # 这里可以直接使用xref和yref做后续处理,比如存入列表
            xref_list.append(xref)
            yref_list.append(yref)
            print(f"提取到:xref={xref}, yref={yref}")

方法二:利用已知行号提取

既然知道目标行的行号是11x - 6(x从1开始),可以直接定位这些行提取数值,提供两种实现方式:

方式A:一次性读取所有行(适合小文件)

xref_list = []
yref_list = []

with open('your_file.txt', 'r') as f:
    all_lines = f.readlines()

x = 1
while True:
    target_line_num = 11 * x - 6
    # 转换为Python列表的索引(行号从1开始,列表索引从0开始)
    line_index = target_line_num - 1
    if line_index >= len(all_lines):
        break  # 超出文件行数就停止循环
    
    target_line = all_lines[line_index].strip()
    num_section = target_line.split('=', 1)[1].strip()
    x_str, y_str = num_section.split(',')
    xref = int(x_str.strip())
    yref = int(y_str.strip())
    
    xref_list.append(xref)
    yref_list.append(yref)
    print(f"提取到:xref={xref}, yref={yref}")
    x += 1

方式B:逐行计数判断(适合大文件,节省内存)

xref_list = []
yref_list = []

with open('your_file.txt', 'r') as f:
    current_line_num = 1  # 行号从1开始计数
    for line in f:
        # 判断当前行号是否符合11x-6的规律
        if (current_line_num + 6) % 11 == 0:
            cleaned_line = line.strip()
            num_section = cleaned_line.split('=', 1)[1].strip()
            x_str, y_str = num_section.split(',')
            xref = int(x_str.strip())
            yref = int(y_str.strip())
            
            xref_list.append(xref)
            yref_list.append(yref)
            print(f"提取到:xref={xref}, yref={yref}")
        current_line_num += 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:15:33