我有一个问题希望防止单引号出现在我的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文件中被单引号引起来。
答案 0 :(得分:3)
endGoal
是输入后的字符串。
在更新YAML之前,尝试使其变成list
中的int
:
endGoal = '[1,2]' # for example
endGoal = [int(a_string) for a_string in endGoal.strip('[]').split(',')]