在Python中解析Yaml:检测重复的键
python中的在Python中解析Yaml:检测重复的键,python,regex,yaml,pyyaml,Python,Regex,Yaml,Pyyaml,python中的yaml库无法检测重复的密钥。这是一个bug,目前还没有修复 我想找到一个解决这个问题的好办法。创建一个返回所有键的regex的可能性有多大?那么就很容易发现这个问题了 任何正则表达式大师都能推荐一个能够提取所有密钥以找到重复项的正则表达式吗 文件示例: mykey1: subkey1: value1 subkey2: value2 subkey3: - value 3.1 - value 3.2 mykey2: subke
yaml
库无法检测重复的密钥。这是一个bug,目前还没有修复
我想找到一个解决这个问题的好办法。创建一个返回所有键的regex
的可能性有多大?那么就很容易发现这个问题了
任何正则表达式大师都能推荐一个能够提取所有密钥以找到重复项的正则表达式吗
文件示例:
mykey1:
subkey1: value1
subkey2: value2
subkey3:
- value 3.1
- value 3.2
mykey2:
subkey1: this is not duplicated
subkey5: value5
subkey5: duplicated!
subkey6:
subkey6.1: value6.1
subkey6.2: valye6.2
命令行工具执行您需要的操作
想要:
具体来说,它有一个规则密钥重复
,用于检测重复和密钥
相互过度书写:
$ yamllint test.yaml
test.yaml
1:1 warning missing document start "---" (document-start)
10:5 error duplication of key "subkey5" in mapping (key-duplicates)
(它有许多其他规则,您可以启用/禁用或调整。)在内置加载程序的基础上进行操作是一种更轻量级的方法:
import yaml
# special loader with duplicate key checking
class UniqueKeyLoader(yaml.SafeLoader):
def construct_mapping(self, node, deep=False):
mapping = []
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
assert key not in mapping
mapping.append(key)
return super().construct_mapping(node, deep)
然后:
他们的执行很糟糕!我同意你的看法,他们应该在构造函数中添加选项。您是否找到了一种以编程方式验证文档的方法?这是一种优雅而直接的方法,与许多需要导入另一个包的建议不同。
import yaml
# special loader with duplicate key checking
class UniqueKeyLoader(yaml.SafeLoader):
def construct_mapping(self, node, deep=False):
mapping = []
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
assert key not in mapping
mapping.append(key)
return super().construct_mapping(node, deep)
yaml_text = open(filename), 'r').read()
data[f] = yaml.load(yaml_text, Loader=UniqueKeyLoader)