Skip to main content
 首页 » 编程设计

python之如何让 pyyaml.safe_load() 处理 python/unicode 标签

2024年10月25日10lovecherry

我们有一种情况,我们在特定情况下使用 yaml 传递一些数据。我们想进一步推出它,我开始我们应该使用 yaml.safe_load()。 yaml 没有什么特别复杂的地方,但是当原始字符串是 unicode 时,我注意到一个特殊的特性。例如:

>>> x = u"hello" 
>>> x 
u'hello' 
>>> yaml.dump(x) 
"!!python/unicode 'hello'\n" 

如果我尝试读入这个,我得到一个异常:

... 
  File "f:\users\---\PyYAML-3.11-py2.7-win-amd64.egg.tmp\yaml\constructor.py", line 414, in construct_undefined yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/unicode' 
  in "<string>", line 1, column 1: 
    !!python/unicode 'hello' 

我看到可以指示 safe_load 支持类,但这不是用户类。我可以切换到使用 safe_dump(),但如果数据由一个工具的旧版本写入并由另一个工具的新版本读取(比方说),那将不起作用。

所以问题:我可以告诉pyyaml它可以加载python unicode字符串吗?

请您参考如下方法:

不知道是否有更简洁的方法,但我找到了答案......

>>> def constructor(loader, node): 
...     return node.value 
... 
>>> yaml.SafeLoader.add_constructor("tag:yaml.org,2002:python/unicode", constructor) 
>>> yaml.safe_load(y) 
u'hello' 
>>> 

我想可能值得检查一下 node.value 实际上是一个 unicode 值,在实际代码中我将其结构略有不同,但这是可行的。 key 正在使用:

yaml.SafeLoader.add_constructor() 

代替:

yaml.add_constructor() 

我猜这会因为使用未记录的 API 而下降,所以任何替代答案都会很有趣。