YAML 转储后出现单引号
Single quote appears after YAML dump
我有一个问题,我希望防止单引号出现在我的 YAML 文件中。无论如何,我可以在没有单引号的情况下实现目标显示的预期输出吗?
我 运行 在 Python 中有以下代码来更新文件:(未实现输入的格式检查,因为这是我正在学习的练习)
import sys
import yaml
import ruamel.yaml
def updateInformation():
agentName = input("What is the name of agent you want to update?")
endGoal = input("What is the new coordinate you want to update, type in terms of [x, y] where x and y are numbers")
updateInputFile(agentName, endGoal)
def updateInputFile(agentName, endGoal):
yaml = ruamel.yaml.YAML()
i = 0
with open('input.yaml') as f:
doc = yaml.load(f)
print(doc)
for v in doc:
if i < len(doc[v]):
if doc['agents'][i]['name'] != agentName:
i = i + 1
pass
else:
if doc['agents'][i]['name'] == agentName:
doc['agents'][i].update({'goal': endGoal})
break
yaml.representer.ignore_aliases = lambda *data: True
with open('input.yaml', 'w') as f:
yaml.dump(doc, f)
当前执行以下代码后的输出文件:
agents:
- start: [0, 0]
goal: '[3, 1]'
name: agent0
- start: [2, 0]
goal: [0, 0]
name: agent1
map:
dimensions: [3, 3]
obstacles:
- !!python/tuple [0, 1]
- !!python/tuple [2, 1]
预期输出:
agents:
- start: [0, 0]
goal: [3, 1]
name: agent0
- start: [2, 0]
goal: [0, 0]
name: agent1
map:
dimensions: [3, 3]
obstacles:
- !!python/tuple [0, 1]
- !!python/tuple [2, 1]
我在想,当它被转储回 YAML 文件时,endGoal 的值面临着作为字符串的模棱两可的解释,导致它在 YAML 文件中被单引号引起来。
endGoal
是输入后的字符串
在更新 YAML 之前尝试将其变成 int
的 list
:
endGoal = '[1,2]' # for example
endGoal = [int(a_string) for a_string in endGoal.strip('[]').split(',')]
我有一个问题,我希望防止单引号出现在我的 YAML 文件中。无论如何,我可以在没有单引号的情况下实现目标显示的预期输出吗?
我 运行 在 Python 中有以下代码来更新文件:(未实现输入的格式检查,因为这是我正在学习的练习)
import sys
import yaml
import ruamel.yaml
def updateInformation():
agentName = input("What is the name of agent you want to update?")
endGoal = input("What is the new coordinate you want to update, type in terms of [x, y] where x and y are numbers")
updateInputFile(agentName, endGoal)
def updateInputFile(agentName, endGoal):
yaml = ruamel.yaml.YAML()
i = 0
with open('input.yaml') as f:
doc = yaml.load(f)
print(doc)
for v in doc:
if i < len(doc[v]):
if doc['agents'][i]['name'] != agentName:
i = i + 1
pass
else:
if doc['agents'][i]['name'] == agentName:
doc['agents'][i].update({'goal': endGoal})
break
yaml.representer.ignore_aliases = lambda *data: True
with open('input.yaml', 'w') as f:
yaml.dump(doc, f)
当前执行以下代码后的输出文件:
agents:
- start: [0, 0]
goal: '[3, 1]'
name: agent0
- start: [2, 0]
goal: [0, 0]
name: agent1
map:
dimensions: [3, 3]
obstacles:
- !!python/tuple [0, 1]
- !!python/tuple [2, 1]
预期输出:
agents:
- start: [0, 0]
goal: [3, 1]
name: agent0
- start: [2, 0]
goal: [0, 0]
name: agent1
map:
dimensions: [3, 3]
obstacles:
- !!python/tuple [0, 1]
- !!python/tuple [2, 1]
我在想,当它被转储回 YAML 文件时,endGoal 的值面临着作为字符串的模棱两可的解释,导致它在 YAML 文件中被单引号引起来。
endGoal
是输入后的字符串
在更新 YAML 之前尝试将其变成 int
的 list
:
endGoal = '[1,2]' # for example
endGoal = [int(a_string) for a_string in endGoal.strip('[]').split(',')]