0

我正在尝试使用 PyYAML 解析 YAML 翻译文件,但某些键使其崩溃:

import yaml
t = yaml.load("%users users have connected: %users users have connected")

错误是"expected alphabetic or numeric character, but found ' '"

4

2 回答 2

0

Search for '%u' on the Python built-in types documentation.

%u is an obsolete string interpolation code that's the same as %d. Python thinks you're trying to interpolate a string. It should parse properly if you were to change it to:

t = yaml.load("%users users have connected: %users users have connected" % users)

It still wouldn't give you what you're probably expecting, though, as the resulting string would be:

10sers users have connected: 10sers users have connected

You can escape the '%' character, or wrap the translation key in curly brackets and use string formatting, like this:

d = {"users": 10}
t = yaml.load("\{users\} users have connected: \{users\} users have connected")

print t.replace('\\','').format(**d)
>>> '10 users'

As mentioned in the comments, you can get it into a string without complaint by escaping the '%'s using:

t = yaml.load(s.replace('%', '\%')).replace('\%', '%')

Where 's' is the string from the translation file.

于 2013-04-22T16:56:47.117 回答
0

我没有得到同样的错误,PyYAML 3.11 和 Python2.7.10 给出:

yaml.parser.ParserError: expected '<document start>', but found '<stream end>'
  in "<string>", line 1, column 57:
     ... ted: %users users have connected

但是您在这里以 a 开头,%并且后面应该跟一个指令。目前只定义了两个指令YAMLTAG并且所有其他字符串都保留以供将来使用

YAML 规范还指出

裸文档不以任何指令或标记行开头。此类文档非常“干净”,因为它们只包含内容。在这种情况下,第一个非注释行可能不以“%”第一个字符开头。

这实际上意味着该字符串%users users have connected: %users users have connected是不正确的 YAML,如果这是一个标量,则必须将其放在引号中。但是我希望以下是正确的 YAML:

- %users users have connected: %users users have connected

但 PyYAML 不接受它,您也必须在此处使用引号。

于 2015-06-23T18:36:13.960 回答