[英]How to skip lines when reading a yaml file in python?
我熟悉類似的問題,但它們似乎並沒有解決應該是一個簡單的問題。 我正在使用Python 2.7x並嘗試讀取類似於此的YAML文件:
%YAML:1.0
radarData: !!opencv-matrix
rows: 5
cols: 2
dt: u
data: [0, 0, 0, 0, 0, 10, 5, 3, 1, 22]
現在我只需要'data:'文檔。 我嘗試了一種vanilla方法然后嘗試強制跳過前4行(第二個被注釋掉的代碼片段)。 兩種方法都有錯誤。
import yaml
stream = file('test_0x.yml', 'r')
yaml.load(stream)
# alternative code snippet
# with open('test_0x.yml') as f:
# stream = f.readlines()[4:]
# yaml.load(stream)
關於如何跳過前幾行的任何建議都將非常感激。
實際上,你只需要跳過前兩行。
import yaml
skip_lines = 2
with open('test_0x.yml') as infile:
for i in range(skip_lines):
_ = infile.readline()
data = yaml.load(infile)
>>> data
{'dt': 'u', 'rows': 5, 'data': [0, 0, 0, 0, 0, 10, 5, 3, 1, 22], 'cols': 2}
>>> data['data']
[0, 0, 0, 0, 0, 10, 5, 3, 1, 22]
跳過前5行也行。
我在這里完全忽略了這一點,但我將原來的答案留在底部作為一個謙卑的提醒。
莫霍克的答案簡短而甜蜜,可能更可取。 一個更復雜的解決方案:剝離格式錯誤的指令,更正自定義標記,並為其添加構造函數。 這樣做的好處是可以在文件中出現的任何位置校正該標記,而不僅僅是在前幾行中。
我在這里的實現確實有一些缺點 - 它會玷污整個文件,並且尚未在復雜數據上進行測試,其中用正確的數據替換標記的效果可能與預期的結果不同。
import yaml
def strip_malformed_directive(yaml_file):
"""
Strip a malformed YAML directive from the top of a file.
Returns the slurped (!) file.
"""
lines = list(yaml_file)
first_line = lines[0]
if first_line.startswith('%') and ":" in first_line:
return "\n".join(lines[1:])
else:
return "\n".join(lines)
def convert_opencvmatrix_tag(yaml_events):
"""
Convert an erroneous custom tag, !!opencv-matrix, to the correct
!opencv-matrix, in a stream of YAML events.
"""
for event in yaml_events:
if hasattr(event, "tag") and event.tag == u"tag:yaml.org,2002:opencv-matrix":
event.tag = u"!opencv-matrix"
yield event
yaml.add_constructor("!opencv-matrix", lambda loader, node: None)
with open("test_0x.yml") as yaml_file:
directive_processed = strip_malformed_directive(yaml_file)
yaml_events = yaml.parse(directive_processed)
matrix_tag_converted = convert_opencvmatrix_tag(yaml_events)
fixed_document = yaml.emit(matrix_tag_converted)
data = yaml.load(fixed_document)
print data
原始答案
你正在使用的yaml.load
函數返回一個字典,可以這樣訪問:
import yaml
with open("test_0x.yml") as yaml_file:
test_data = yaml.load(yaml_file)
print test_data["data"]
這有幫助嗎?
我有aruco_calibration_fromimages.exe生成的相機矩陣,這里是yml文件:
%YAML:1.0
---
image_width: 4000
image_height: 3000
camera_matrix: !!opencv-matrix
rows: 3
cols: 3
dt: d
data: [ 3.1943912478853654e+03, 0., 1.9850941722590378e+03, 0.,
3.2021356095317910e+03, 1.5509955246019449e+03, 0., 0., 1. ]
distortion_coefficients: !!opencv-matrix
rows: 1
cols: 5
dt: d
data: [ 1.3952810090687282e-01, -3.8313647492178071e-01,
5.0555840762660396e-03, 2.3753464602670597e-03,
3.3952514744179502e-01 ]
使用以下代碼加載此yml:
import cv2
fs = cv2.FileStorage("./calib_asus_chess/cam_calib_asus.yml", cv2.FILE_STORAGE_READ)
fn = fs.getNode("camera_matrix")
print(fn.mat())
得到這個結果:
[[ 3.19439125e+03 0.00000000e+00 1.98509417e+03]
[ 0.00000000e+00 3.20213561e+03 1.55099552e+03]
[ 0.00000000e+00 0.00000000e+00 1.00000000e+00]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.