使用ruamel.yaml我試圖讓在特定式樣下的YAML,更具體地一個,其中單一行的字符串在同一行:
和多行字符串開始使用摺疊標量樣式(|
/|-
)和線受限於一定數量的字符(文字包裝)。將YAML多行值轉換爲摺疊塊標量樣式?
我嘗試到目前爲止很大程度上由similar function called walk_tree
in the sources影響:
#!/usr/bin/env python
import ruamel.yaml
from ruamel.yaml.scalarstring import ScalarString, PreservedScalarString
def walk_tree(base):
from ruamel.yaml.compat import string_types
if isinstance(base, dict):
for k in base:
v = base[k]
if isinstance(v, string_types):
v = v.replace('\r\n', '\n').replace('\r', '\n').strip()
base[k] = ScalarString(v) if '\n' in v else v
else:
walk_tree(v)
elif isinstance(base, list):
for idx, elem in enumerate(base):
if isinstance(elem, string_types) and '\n' in elem:
print(elem) # @Anthon: this print is in the original code as well
base[idx] = preserve_literal(elem)
else:
walk_tree(elem)
with open("input.yaml", "r") as fi:
inp = fi.read()
loader=ruamel.yaml.RoundTripLoader
data = ruamel.yaml.load(inp, loader)
walk_tree(data)
dumper = ruamel.yaml.RoundTripDumper
with open("output.yaml", "w") as fo:
ruamel.yaml.dump(data, fo, Dumper=dumper, allow_unicode=True)
但後來我得到一個異常:ruamel.yaml.representer.RepresenterError: cannot represent an object: …
。如果我將ScalarString
替換爲PreservedScalarString
,與原始walk_tree
代碼中的情況一樣,我也不例外,但是我再次得到了不是我想要的文字塊。
那麼我的代碼如何修復以便它能夠工作?
默認以上增加72至'print'呼叫將在0.13.8消失了,謝謝指出。 – Anthon
如果我的回答不能滿足您的需求,請將樣品輸入(並輸出,如果不同)YAML文件,請將其編輯到您的問題中。如果你這樣做,你不應該放入* EDIT *。留下一個簡短的評論,這將觸發通知。 – Anthon