全文检索关键字

# -*- coding: utf-8 -*-
"""
1、获取excel表中api接口名称列表
2、在封装的接口库中比对搜索关键字
3、接口名存在记为1,否则为0,写入excel表中
"""

import xlwt, xlrd
import io

# 记录列数,全局变量,还原方便
columnIndex = 0
# 记录行数
rowIndex = 1
# 记录任务个数
taskCount = 0


# 读excel
def ReadExcel(filepath):
    xlsx = xlrd.open_workbook(filepath)  # 打开文件
    print('All sheets: %s' % xlsx.sheet_names())  # 查看所有sheet列表
    sheet1 = xlsx.sheets()[1]  # 获得第1张sheet,索引从0开始
    sheet1_name = sheet1.name  # 获得名称
    sheet1_cols = sheet1.ncols  # 获得列数
    sheet1_nrows = sheet1.nrows  # 获得行数
    print('Sheet1 Name: %s\nSheet1 cols: %s\nSheet1 rows: %s' % (sheet1_name, sheet1_cols, sheet1_nrows))
    print('-----------------接口列表----------------')
    api_name = []
    for i in range(1, sheet1_nrows):  # 逐行打印sheet1数据
        print(sheet1.row_values(i))   # 打印全文
        if sheet1.row(i)[1].value != '':  # 读取2列
            api_name.append(sheet1.row(i)[1].value.encode('UTF-8'))   # 读取的excel值是unicode字符集转uft8编码
            #api_name.append(sheet1.row(i)[1].value)
    print(api_name)
    return api_name

# 直接读取文件内容检索,适合一般大小文件
def content_search1(filepath, keyword):
    with open(filepath, 'r') as f:
        content = f.read()
    #print(content)
    if keyword in content:
        return True
    return False

# 按行检索关键字,适合大文件
def content_search(filepath, keyword):
    f = open(filepath, 'r')
    for line in f:
        if keyword in line:
            f.close()
            return True
    f.close()
    return False


if __name__ == '__main__':

    # 读取api接口名
    filepath = 'Hub接口用例情况统计.xlsx'
    api_name_list = ReadExcel(filepath)

    # 用例地址
    file_path = 'iot_hub.py'

    # 使用xlwt模块
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('统计', cell_overwrite_ok=True)

    title_list = ['接口名', '是否封装']

    # 用例标题写入excel首行
    for j in range(0, len(title_list)):
        ws.write(0, j, title_list[j])
        j += 1
    r_true = 0
    r_false = 0
    for i in range(0, len(api_name_list)):
        api_name = api_name_list[i]  # 检索的keyword
        flag = content_search(file_path, api_name_list[i])  # 是否存在
        if flag:
            r_true += 1
        else:
            r_false += 1
        taskCount += 1  # 任务个数
        ws.write(rowIndex, columnIndex, api_name)  # 写任务id
        ws.write(rowIndex, columnIndex + 1, flag)  # 写任务name
        i += 1

        rowIndex += 1

    print('任务总数%s:' % taskCount)
    print('True %d False %d', r_true, r_false)

    # 保存Excel文档
    wb.save('统计表.xls')

  

posted @ 2022-04-07 10:09  ReluStarry  阅读(31)  评论(0编辑  收藏  举报