删除字典对象周围的双引号 - python

remove double quotes around dictionary object - python

我有一本字典,用于为每个键填充 YAML 配置文件。

{'id': ['HP:000111'], 'id1': ['HP:000111'], 'id2': ['HP:0001111', 'HP:0001123'])}

使用 ruamel.yaml

将 key:value 对插入 YAML 模板的代码
import ruamel.yaml
import sys

yaml = ruamel.yaml.YAML()
with open('yaml.yml') as fp:
    data = yaml.load(fp)

for k in start.keys():
    data['analysis']['hpoIds'] = start.get(key)
       with open(f"path/yaml-{k}.yml","w+") as f:
           yaml.dump(data, sys.stdout)

这是我得到的输出

analysis:
    # hg19 or hg38 - ensure that the application has been configured to run the specified assembly otherwise it will halt.
  genomeAssembly: hg38
  vcf:
  ped:
  proband:
  hpoIds: "['HP:000111','HP:000112','HP:000113']"

但这正是我需要的

  hpoIds: ['HP:000111','HP:000112','HP:000113']

我尝试过使用字符串工具,即剥离、替换但没有

来自ast.literal_eval.

的输出
hpoIds:
  - HP:000111
  - HP:000112
  - HP:000113

来自repr

的输出
hpoIds: "\"['HP:000111','HP: 000112','HP:000113']\""

任何帮助将不胜感激

我不完全清楚你想做什么以及你为什么打开文件 'w+' 用于倾销。

但是,如果您有一些块样式且未引用的内容,则可以轻松修复 通过使用一个小函数:

import sys
from pathlib import Path
import ruamel.yaml

SQ = ruamel.yaml.scalarstring.SingleQuotedScalarString

def flow_seq_single_quoted(lst):
    res = ruamel.yaml.CommentedSeq([SQ(x) if isinstance(x, str) else x for x in lst])
    res.fa.set_flow_style()
    return res

in_file = Path('yaml.yaml') 
in_file.write_text("""\
hpoIds:
  - HP:000111
  - HP:000112
  - HP:000113
""")

yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)
data['hpoIds'] = flow_seq_single_quoted(data['hpoIds'])

yaml.dump(data, sys.stdout)

给出:

hpoIds: ['HP:000111', 'HP:000112', 'HP:000113']

至少从 2006 年 9 月开始,YAML 文件的推荐扩展名是 .yaml