求助:如何用Python提取文件Header中的size与top数值
提取Header中的size和top数值解决方案
先修正你原代码里的小问题:函数参数input未被使用,却直接引用了外部的input1,同时line初始化为列表完全没必要。下面提供两种可靠的提取方法:
方法一:字符串分割解析
适合格式固定的键值对场景,步骤清晰直观:
import sys def readinput(file): # 读取一行并去除首尾空白(包括换行符) line = file.readline().strip() # 将行内容按空格分割成单个键值对 key_value_pairs = line.split() size = None top = None for pair in key_value_pairs: # 拆分键和值 key, value = pair.split('=') if key == 'size': size = int(value) elif key == 'top': top = int(value) print(f"提取结果:size = {size}, top = {top}") return size, top with open(sys.argv[1], 'r') as input1: size, top = readinput(input1)
方法二:正则表达式匹配
适合Header格式有微小变动(比如空格数量变化)的场景,灵活性更强:
import sys import re def readinput(file): line = file.readline().strip() # 用正则匹配size和top对应的数值,支持正负整数 pattern = r'size=(\d+) top=(-?\d+)' match_result = re.match(pattern, line) if match_result: size = int(match_result.group(1)) top = int(match_result.group(2)) print(f"提取结果:size = {size}, top = {top}") return size, top else: print("错误:Header格式不符合预期") return None, None with open(sys.argv[1], 'r') as input1: size, top = readinput(input1)
两种方法都能准确提取size和top的数值并转换为整数类型,可根据实际情况选择使用。
内容的提问来源于stack exchange,提问作者Felipe Lorusso
相关产品推荐
相关产品推荐

