python - 解析 CS :GO script file in Python

标签 python parsing format

我正在使用 CS:GO 中的一些脚本文件,我必须从该文件中获取一些有用的信息并将这些数据导入到我的 Python 应用程序中。

这里是一个txt数据格式的例子:

https://steamcdn-a.akamaihd.net/apps/730/scripts/items/items_game.83a9ad4690388868ab33c627af730c43d4b0f0d9.txt

这些值采用随机格式 (Color\Pos\String),但我只需要一个包含所有值的字符串。 我需要将这些信息放入字典中,例如:

print(global_dict['items_game']['game_info']['first_valid_class'])
<<2

我现在正在研究解析器,但我遇到了很多问题。该文件格式是否有现成的解决方案?

最佳答案

作为CoryKramer指出,该文件几乎 JSON。

因此,我在下面编写了一个自定义解析器,它通过逐行读取源配置并将正确的 JSON 格式写入输出文件来解析文件。

我什至使用 JSONLint 测试了输出并且文件已成功验证。

Note: This code was written to parse any of the files located in:

%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

关于python - 解析 CS :GO script file in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35946793/

相关文章:

python - SQLAlchemy,对多个表使用相同的模型

python - svmLight 格式中每一项的含义是什么

python - 在 python 中使用 format(**locals()) 插入之前操作值

java - 在Java中将字符串转换为日期并根据当前日期进行排序。

java - Java 的 SQL 解析器库

Python csv_writer : Change the output format of a oracle date column

python - 如何将乌尔都语语言字符保存在 csv 文件中?

python - 卷积自动编码器未在 (62,47,1) 数据集上训练, "Expected Shape Error"

python - Nginx + Gunicorn + Flask : How to figure out the real base URL

php - PHP解析/语法错误;以及如何解决它们