混合文本数据和配置文件的分析器
wcfg的Python项目详细描述
wcfg是一个小模块,用于分析来自文本文件的分层数据,它 尤其适用于配置文件。
功能:
- 基于文本的分层格式,具有简单的语法,用于 很容易被程序和人解析。
- 支持读取和写回。保证书面数据 使其可读性恢复到原来的表示形式。
- 小型的、自包含的、纯python实现。
- 与Python2.6和3.2(或更新版本)兼容。
示例
给定以下输入文件:
# Configuration file for SuperFooBar v3000 interface { language: "en_US" panes { top: ["menu", "toolbar"] # Optional commas in lists # The colon separating keys and values is optional bottom ["statusbar"] } ☺ : True # Enables emoji Unicode→Suþþorteð? : "Indeed, Jürgen!" } # Configure plug-ins plugin: { preview # Whitespace is mostly ignored { enabled: true timeout: 500 # Update every 500ms } }
注意,键和值之间的:分隔符是可选的,并且 可以省略。另外,请注意空格(包括新行)是如何 完全没有意义,结构只能用大括号来确定 和括号。最后但并非最不重要的是,有效的键是任何unicode字符 不包含空格或冒号的序列。
以下代码可用于将其读入python字典:
importwcfgwithopen("superfoobar3000.conf","rb")asf:config=wcfg.load(f)
转换按预期工作:
- 节被转换成字典。
- 键被转换为字符串。
- 双引号中的文本将转换为字符串。
- 封装在{ }中的节将转换为字典。
- 封装在[ ]中的数组将转换为列表。
- 数字转换为int或float,以较大者为准 适当的。
- 布尔值转换为bool。
以下内容可用于将python字典转换为其文本 表示:
users={"peter":{"uid":1000,"name":"Peter Jøglund","groups":["wheel","peter"],},"root":{"uid":0,"groups":["root"],}}importwcfgtext=wcfg.dumps(users)
生成文本表示时,每个字典的键将 进行排序,以确保生成的输出是稳定的。字典 前面的片段将以如下文本形式编写:
peter: { name: "Peter Jøglund" groups: ["wheel" "peter"] uid: 1000 } root: { groups: ["root"] uid: 0 }
语法
这是语法分析器接受的语法,在EBNF syntax:
identifier = - ( whitespace | ":" ) string character = - "\"" key-value pair = identifier, ":", value | identifier, value octal digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" digit = octal digit | "8" | "9" hexdigit = digit | "a" | "b" | "c" | "d" | "e" | "f" | "A" | "B" | "C" | "D" | "E" | "F" sign = "-" | "+" integral number = digit, { digit } dotted float = ".", digit, { digit } | digit, ".", { digit } exponent = ("e" | "E"), sign, digit, { digit } | ("e" | "E"), digit, { digit } float number = dotted float | dotted float, exponent | integral number, exponent number body = integral number | float number number = "0", ( "x" | "X" ), hex digit, { hex digit } | "0", octal digit, { octal digit } | sign, number body | number body boolean = "True" | "False" | "true" | "false" value = "\"", { string character }, "\"" | "[", { (value | value ",") } "]" | "{", { key-value pair }, "}" | boolean | number input = "{", { key-value pair }, "}" | { key-value pair }
注意,上面的语法中没有指定注释,不包括 为了简单起见的评论。注释可以出现在除 在字符串内部,它们从octothorpe符号(#)到 排队。