As 科里·克莱默指出,该文件是almost JSON.
因此,我在下面编写了一个自定义解析器,它通过逐行读取源配置并将正确的 JSON 格式写入输出文件来解析文件。
我什至使用测试了输出JSONLint并且文件已成功验证。
Note:编写此代码是为了解析位于以下位置的任何文件:
%STEAMINSTALL%/SteamApps/common/Counter-Strike Global Offensive/csgo/scripts
要使用以下脚本,请执行:
$ ConfigParser.py -h
usage: ConfigParser.py [-h] [-s SRC] dest
positional arguments:
dest file where the parsed JSON will be written to
optional arguments:
-h, --help show this help message and exit
-s SRC, --src SRC source config file
#!/usr/bin/env python3
"""ConfigParser.py: Parses a Valve configuration file.
The configuration file for the CS:GO game items is read line-by-line
and written to an output file. The missing colons and commas are added
to their appropriate places. The output file passed JSLint validation.
"""
from argparse import ArgumentParser
from shlex import split
__author__ = "Mr. Polywhirl"
__copyright__ = "Copyright 2016, Stack Overflow"
__credits__ = []
__license__ = "GPLv3"
__version__ = "1.1.0"
__maintainer__ = "Mr. Polywhirl"
__email__ = "https://stackoverflow.com/users/1762224"
__status__ = "Production"
# This is the default file that is parsed.
DEFAULT_CONFIG_FILE = 'C:/Program Files (x86)/Steam/steamapps/common/\
Counter-Strike Global Offensive/csgo/scripts/items/items_game.txt'
def parseConfig(src_filename, dest_filename):
out_file = open(dest_filename, 'w')
indent_ch = '\t'
curr_level = 1
out_file.write('{\n')
with open(src_filename, 'r') as f:
for line in f.readlines():
if line.strip().startswith('//'):
continue # Skip comments.
level = line.find('"') + 1
if level < 1:
continue # Skip lines without tokens.
values = ['"' + v + '"' for v in split(line)]
indent = indent_ch * level
if level != curr_level:
delta = curr_level - level
curr_level = level
if delta > 0:
for i in range(delta, 0, -1):
out_file.write('\n' + (indent_ch * (level + i - 1)) + '}')
if i == 1:
out_file.write(',')
out_file.write('\n')
elif level == curr_level and level > 1:
out_file.write(',\n')
if len(values) == 1:
out_file.write(indent + values[0] + ' : {\n')
else:
out_file.write(indent + ' : '.join(values))
for i in range(curr_level, 0, -1):
out_file.write('\n' + (indent_ch * (level + i - 1)) + '}')
out_file.close()
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('-s', '--src', default=DEFAULT_CONFIG_FILE, help="config file")
parser.add_argument('dest', help="file where the parsed JSON will be written to")
args = parser.parse_args()
parseConfig(args.src, args.dest)
补充笔记
似乎有一个用 Java 编写的 CS:GO 配置解析器,它使用 Antlr 语法来解析文件。
GitHub项目链接:https://github.com/valx76/CSGO-Config-Parser