簡體   English   中英

在用 Python 將字典寫入 YAML 文件時,如何確保 YAML 文件中的字符串根據 '\n' 進行拆分?

[英]When writing in Python a dictionary to a YAML file, how to make sure the string in the YAML file is split based on '\n'?

我在字典中有一個長字符串,我會將其轉儲到 YAML 文件中。

舉個例子

d = {'test': {'long_string':'this is a long string that does not succesfully split when it sees the character '\n' which is an issue'}}
ff = open('./test.yaml', 'w+')
yaml.safe_dump(d, ff)

在 YAML 文件中產生以下輸出

 test:
      long_string: "this is a long string that does not successfully split when it sees\
\ the character '\n' which is an issue" 

我希望 YAML 文件中的字符串僅在看到“\n”時才拆分為新行,而且,我不希望任何字符表明它是換行符。 我想要如下輸出:

 test:
      long_string: "this is a long string that does not successfully split when it sees the character '' 
                    which is an issue"

我需要做什么才能使yaml.dumpyaml.safe_dump實現這一點?

沒有通用的解決方案。 YAML 是一種有意設計的格式,讓實現決定值的確切表示。

您可以做的是建議一種格式。 如果可能的話,傾銷者會尊重這個建議。 一種標量格式在值的文字換行符處中斷,而在其他任何地方都是文字塊標量。 如果可能,此代碼將轉儲您的字符串:

import yaml, sys

class as_block(str):
    @staticmethod
    def represent(dumper, data):
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')

yaml.SafeDumper.add_representer(as_block, as_block.represent)

d = {'test': {'long_string':as_block('this is a long string that does not succes
fully split when it sees the character\n which is an issue')}}
yaml.safe_dump(d, sys.stdout)

輸出:

test:
  long_string: |-
    this is a long string that does not succesfully split when it sees the character
     which is an issue

我將as_block用於應寫為塊標量的字符串。 理論上您可以將它用於所有字符串,但請注意long_stringtest也將被編寫為塊標量,這很可能不是您想要的。

當換行符前有空格時,這將不起作用,因為 YAML 會忽略塊標量一行末尾的空格,因此序列化程序將選擇另一種格式來不丟失空格字符。

您也可以退后一步,問問自己為什么這首先是一個問題。 YAML 實現完全能夠加載生成的 YAML 並重建您的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM