语句提取数据存入excel


import re
from re import X
import xlwt
import xlrd


def calculate_average(lst):
    # print(lst)
    sum = 0
    acc = 0
    for val in lst:
        if(val == ''):
            continue
        sum += int(val)
        acc += 1
    if(acc == 0):
        return 0
    return sum/acc


def find_num(str, pattern):
    p_1 = re.compile(pattern)
    raw_1 = p_1.findall(str)
    str = "".join(raw_1)
    p_2 = re.compile("[0-9]+")
    return p_2.findall(str)


def write_file(val, key):
    book = xlwt.Workbook(encoding='utf-8')  # 创建Workbook,相当于创建Excel

    # 创建sheet,Sheet1为表的名字,cell_overwrite_ok为是否覆盖单元格
    sheet1 = book.add_sheet(u'Sheet1', cell_overwrite_ok=True)

    for i in range(len(key)):
        sheet1.write(0, i+1, key[i])

    row = 1
    for i in range(len(val[0])):
        for j in range(len(val)):
            sheet1.write(row, j+1, val[j][i])
        row = row+1

    # write average
    sheet1.write(row, 0, "average")
    for i in range(len(key)):
        sheet1.write(row, i+1, calculate_average(val[i]))

    book.save('/Users/bytedance/Documents/csv_1.0.xls')


if __name__ == '__main__':
    key = ["Lock", "eglmake", "draw", "buf", "render", "all"]

    with open('/Users/bytedance/Documents/csv_1.0.log', 'r+') as fd:
        val = [[] for i in range(len(key))]
        # for i in range(len(key)):
        # val[i].append([])
        # val[i].pop()

        for text in fd.readlines():
            # print(text)
            for i in range(len(key)):
                v = find_num(text, key[i]+": [0-9]+")
                # print(v)
                if(v != ''):
                    val[i].append("".join(v))

        write_file(val, key)

文章作者: ZhongSY
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ZhongSY !
评论
  目录