python - 在 yaml.dump Python 中强制引号

标签 python string yaml quotes

在我进入之前,是的,我已经研究过它并且知道 YAML 不区分引号和非引号并且只接受它们的类型。坦率地说,我认为没有引号更好,但不幸的是,这不是我需要的。所以请尝试理解我已经调查了此事,但​​仍然需要在我的字符串对象周围加上引号。

在我的代码中我有一个字典:

data = {dic:[{A:''}, {B:''}, {C:''}, {D:''},...]}

'var*' 是通过 PyQt4 QLineEdit 类构建的,代码行提取行如下所示:

var* = str(QtGui.QLineEdit().displayText())

所以当我执行 data['dic'][index]['A'-'Z'] = var*

它变成了 data = {dic:[{A: 'var1'}, {B:'var2'}, {C:'var3'}, {D:'var4'},...] }

然后我转储我所有的数据:

prettyData = yaml.dump(data, default_flow_style=False, width=10000000)

print prettyData 我明白了:

dic:
  - A: var1
  - B: var2
  - C: var3
  - D: var4
  ...

我尝试了很多方法让它们出现:

dic:
  - A: 'var1'
  - B: 'var2'
  - C: 'var3'
  - D: 'var4'
  ...

但还没有成功。我听到过关于此事的不同意见,从“不可能”到“只是在它们周围加上引号”,如您所见,就我而言,我做不到。

关于如何解决这个问题有什么想法吗?

最佳答案

您可以覆盖标量的发射器并更改动态发射值的样式。根据您拥有的其余标量值,您可能需要进行更多测试以取消设置 is_string。当 process_scalar 被调用时,您不再知道原始值,您只有一个带有 (unicode) 字符串值的事件。

import sys
import ruamel.yaml as yaml

yaml_str = """\
dic:
  - A: var1    # need to get these strings quoted
  - B: var2
  - C: var3
  - D: var4
  - E: 3       # leave this alone
"""

# the scalar emitter from emitter.py
def process_scalar(self):
    if self.analysis is None:
        self.analysis = self.analyze_scalar(self.event.value)
    if self.style is None:
        self.style = self.choose_scalar_style()
    split = (not self.simple_key_context)
    # VVVVVVVVVVVVVVVVVVVV added
    if split:  # not a key
        is_string = True
        if self.event.value and self.event.value[0].isdigit():
            is_string = False
        # insert extra tests for scalars that should not be ?
        if is_string:
            self.style = "'"
    # ^^^^^^^^^^^^^^^^^^^^
    # if self.analysis.multiline and split    \
    #         and (not self.style or self.style in '\'\"'):
    #     self.write_indent()
    if self.style == '"':
        self.write_double_quoted(self.analysis.scalar, split)
    elif self.style == '\'':
        self.write_single_quoted(self.analysis.scalar, split)
    elif self.style == '>':
        self.write_folded(self.analysis.scalar)
    elif self.style == '|':
        self.write_literal(self.analysis.scalar)
    else:
        self.write_plain(self.analysis.scalar, split)
    self.analysis = None
    self.style = None
    if self.event.comment:
        self.write_post_comment(self.event)

data = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)
dd = yaml.RoundTripDumper
dd.process_scalar = process_scalar
yaml.dump(data, sys.stdout, Dumper=dd)

并得到输出¹:

dic:
- A: 'var1'    # need to get these strings quoted
- B: 'var2'
- C: 'var3'
- D: 'var4'
- E: 3         # leave this alone

¹ 这是使用 ruamel.yaml 完成的我是其中的作者。那个包是 PyYAML 的增强。您也许可以对后者执行类似的操作,但它会删除输入中的评论。

关于python - 在 yaml.dump Python 中强制引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27947653/

相关文章:

java - 将数组 ( String[] ) 表示为带有范围的字符串 CSV

ruby 轨道 : Can you put Ruby code in a YAML config file?

encryption - 在公共(public)存储库中使用 Travis-CI 构建通知 Hook 保持 API key 完整性

python - PyCharm Django 测试运行程序看不到 django.sites(运行时错误)

python - 如何在matplotlib 3d plot中实现透视

c# - 为什么以下字符串比较代码在附加 0x81 后返回 TRUE

python - 从文件加载特定的 PyYAML 文档

python - 如何在 python 中定义数组?

python - matplotlib 绘图速度非常慢

java - 简化代码 - 检查字符串中的第一个字符以匹配字符列表