PyYaml 将 '9:00' 解析为 int [英] PyYaml parses '9:00' as int

查看:25
本文介绍了PyYaml 将 '9:00' 解析为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下数据的文件:

I have a file with the following data:

classes:
  - 9:00
  - 10:20
  - 12:10

(以此类推直到 21:00)

(and so on up to 21:00)

我使用 python3 和 yaml 模块来解析它.准确地说,源代码是 config = yaml.load (open (filename, 'r')).但是,当我 print config 时,我得到了这部分数据的以下输出:

I use python3 and yaml module to parse it. Precisely, the source is config = yaml.load (open (filename, 'r')). But then, when I print config, I get the following output for this part of data:

'classes': [540, 630, 730, 820, 910, 1000, 1090, 1180],

列表中的值为整数.

虽然以前,当我使用 python2(以及用于 YAML 的 BaseLoader)时,我以字符串形式获取值,并按原样使用它们.BaseLoader 现在是不可接受的,因为我想从文件中读取 unicode 字符串,它给了我字节字符串.

While previously, when I used python2 (and BaseLoader for YAML), I got the values as strings, and I use them as such. BaseLoader is now not acceptable since I want to read unicode strings from file, and it gives me byte-strings.

那么,首先,为什么 pyyaml 会将我的数据解析为整数?

So, first, why pyyaml does parse my data as ints?

第二,我如何防止 pyyaml 这样做?是否可以不更改数据文件(例如不添加!!str)来做到这一点?

And, second, how do I prevent pyyaml from doing this? Is it possible to do that without changing data file (e.g. without adding !!str)?

推荐答案

您可能应该检查 YAML 的文档

冒号用于映射值.

我想你想要一个字符串而不是一个整数,所以你应该双引号你的字符串.

I presume you want a string and not an integer, so you should double quote your strings.

这篇关于PyYaml 将 '9:00' 解析为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆