代码之家  ›  专栏  ›  技术社区  ›  JohnDoe

从python解析C数组的优雅方法

  •  -1
  • JohnDoe  · 技术社区  · 7 年前

    有什么优雅的方法可以解析C数组并将具有定义索引的元素提取到out文件中。

    例如:

    我的文件。c

    my_array[SPECIFIC_SIZE]={
    0x10,0x12,0x13,0x14,0x15,0x23,0x01,0x02,0x04,0x07,0x08,
    0x33,0x97,0x52,0x27,0x56,0x11,0x99,0x97,0x95,0x77,0x23,
    0x45,0x97,0x90,0x97,0x68,0x23,0x28,0x05,0x66,0x99,0x38,
    0x11,0x37,0x27,0x11,0x22,0x33,0x44,0x66,0x09,0x88,0x17,
    0x90,0x97,0x17,0x90,0x97,0x22,0x77,0x97,0x87,0x25,0x22,
    0x25,0x47,0x97,0x57,0x97,0x67,0x26,0x62,0x67,0x69,0x96
    }
    

    Python脚本:

    我想做一些类似的事情(就像伪代码一样)

    def parse_data():
        outfile = open(newfile.txt,'w')
        with open(myfile, 'r')
        SEARCH FOR ELEMENT WITH INDEX 0 IN my_array
            COPY ELEMENT TO OUTFILE AND LABEL WITH "Version Number"
    
        SEARCH FOR ALL ELEMENTS WITH INDEX 1..10 IN my_array
            COPY ELEMENTS TO OUTFILE WITH NEW LINE AND LABEL with "Date"
    
       ....
       ....
    

    最后,我想有一个新的文件。类似txt:

    Version Number:
    0x10
    
    Date:
    0x12,0x13,0x14,0x15,0x23,0x01,0x02,0x04,0x07,0x08
    

    你能给出一个伪代码的例子吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   IMCoins    7 年前

    如果您的 .c 文件的解析方式始终如下所示:

    • 第一行是数组的声明。
    • 中间线是数据。
    • 最后一行是右括号。

    你可以。。。

    def parse_myfile(fileName; outName):
        with open(outName, 'w') as out:
            with open(fileName, 'r') as f:
                """ 1. Read all lines, except first and last.
                    2. Join all the lines together.
                    3. Replace all the '\n' by ''.
                    4. Split using ','.
                """
                lines = (''.join(f.readlines()[1:-1])).replace('\n', '').split(',')
    
                header = lines[0]
                date = lines[1:11]
            out.write('Version Number:\n{}\n\nDate:\n{}'.format(header, date))
    
    if __name__ == '__main__':
        fileName = 'myfile.c'
        outFile = 'output.txt'
        parse_myfile(fileName, outFile)
    

    cat output.txt 输出。。。

    Version Number:
    0x10
    
    Date:
    ['0x12', '0x13', '0x14', '0x15', '0x23', '0x01', '0x02', '0x04', '0x07', '0x08']