python之路

python实现文件关键字扫描工具

2021-06-23  本文已影响0人  非鱼2018

效果:


image.png

搜索关键字并生成问题报告

源码:

# coding=utf-8
# 搜索关键字
import os
import jinja2
import matplotlib.pyplot as plt
import matplotlib as mpl
from jinja2 import PackageLoader, Environment, FileSystemLoader
from bs4 import BeautifulSoup as BS

def search_key(fileptah,key,exclude_dir=None):
    bugs_info=[]
    all_files=[]
    for root,dirpath,files in os.walk(fileptah):
        print(root)
        for file in files:
            file_path=os.path.join(root,file)
            all_files.append(file_path)
            for rows,lines in enumerate(open(file_path,'r').readlines(),start=1):
                if key in lines:
                    bugs_info.append("{}-{}-{}".format(file_path,rows,lines))
                else:
                    continue
    return bugs_info,all_files


def create_pie(*args):


    mpl.rcParams["font.sans-serif"] = ["SimHei"]
    mpl.rcParams["axes.unicode_minus"] = False

    elements = ["文件数", "问题数"]

    weight=args
    #weight = [40, 15]
    # colors = ["#377eb8", "#4daf4a"]
    explode = (0, 0.1)  # 离开中心距离
    #使饼图显示数字而不是百分比
    def make_autopct(values):
        def my_autopct(pct):
            total = sum(values)
            val = int(round(pct * total / 100.0))
            return '{v:d}'.format(v=val)

        return my_autopct

    colors = ['green', 'red']
    wedges, texts, autotexts = plt.pie(weight,explode=explode,
                                       textprops=dict(color="w"), autopct=make_autopct(weight), colors=colors
                                       )
    plt.legend(wedges,elements,fontsize=12,loc="upper center",
               bbox_to_anchor=(0.91, 0, 0.3, 1))

    plt.setp(autotexts, size=15, weight="bold")
    plt.setp(texts, size=12)
    plt.title("扫描报告")
    #plt.show()
    import time
    img_path='pie-{}.png'.format(round(time.time()))
    plt.savefig(img_path,figsize=[5, 5])
    img_path=os.path.normpath(os.path.join(os.path.dirname(__file__),img_path))
    return img_path


def main(file_dir):
    
    res, all_files = search_key(file_dir, 'china')
    results = []

    for i in res:
        res_dict = {}
        file_path, lines_number, buginfo = i.split('-')
        res_dict["file_path"] = file_path
        res_dict["lines_number"] = lines_number
        res_dict["buginfo"] = buginfo
        results.append(res_dict)

    print(results)
    img_path=create_pie(len(all_files), len(res))
    env = Environment(loader=FileSystemLoader('./templete'))
    template = env.get_template('temp0614.html')
    content = template.render(files_count=len(all_files), bugs_count=len(res), image_url=img_path, bugs=results)
    with open('res0614.html', 'w') as f:
        f.write(content)


if __name__ == '__main__':
    file_dir = r"D:\files"
    main(filedir)

html模板:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>temp1</title>
</head>
<body>
<h1>扫描报告</h1>
<h3>文件个数:{{files_count}}</h3>
<h3>问题个数:{{bugs_count}}</h3>
<img height="240" width="320" src={{image_url}}>
<table border="1">
    <tr><th>文件路径</th><th>行数</th><th>问题</th></tr>
    {% for bug in bugs %}
    <tr>


    <td>{{bug.file_path}}</td><td>{{bug.lines_number}}</td><td>{{bug.buginfo}}</td>

    </tr>
    {% endfor %}
</table>

</body>
</html>

上一篇下一篇

猜你喜欢

热点阅读