Пример #1
0
def createSkippedVulnsOutput():
    """
    sendSkipped = (name, severity, host, ip, path, location, vulnerabilityClassification, confidence)

    """
    # add page break to get this appendix on new line
    document.add_page_break()
    document.add_heading('Additional Vulnerability Details', level=1)

    skippedVulnList.sort()
    for skippedVuln in skippedVulnList:
        skippedVuln = str(skippedVuln)
        confidence = skippedVuln.split(',')[7]
        confidence = confidence.split(')')[0]
        confidence = str(confidence).lower()
        if not confidence == 'tentative':
            skippedVuln = str(skippedVuln)
            skippedVuln = skippedVuln.replace("'", "")
            name = skippedVuln.split(',')[0]
            # stripping the first ( from the issue name in the report.
            name = name.split('(')[1]
            severity = skippedVuln.split(',')[1]
            host = skippedVuln.split(',')[2]
            ip = skippedVuln.split(',')[3]
            path = skippedVuln.split(',')[4]
            location = skippedVuln.split(',')[5]
            confidence = skippedVuln.split(',')[7]
            confidence = confidence.split(')')[0]
            location = str(location)
            orig_location = location
            loc_count = location.count('/')
            if loc_count < 2:
                # full_location = os.path.join(host, location)
                full_location = host + location
                location = full_location
            severity = str(severity)
            severity = severity + ' Risk '
            severity = severity.title()
            build_header = '{} ({})'.format(name, severity)
            status_logger.info('Creating Issue: {}'.format(build_header))
            document.add_heading(build_header, level=3)
            if 'http' in location:
                location = orig_location
            host_url = host + location
            host_url = host_url.replace(' ', '')

            table = document.add_table(rows=1, cols=2)
            # adjusted cell alignment here manually.
            hdr_cells = table.rows[0].cells
            hdr_cells[0].text = 'Vulnerable Host:'
            hdr_cells[0].width = Inches(1.5)
            host = host.strip()
            hdr_cells[1].text = host
            hdr_cells[1].width = Inches(6)
            hdr_cells[1].left_margin = .1
            row_cells = table.add_row().cells
            row_cells[0].text = 'Vulnerable URL:'
            row_cells[0].width = Inches(1.5)
            host_url = host_url.strip()
            row_cells[1].text = host_url
            row_cells[1].width = Inches(6)
            row_cells[1].left_margin = .1
            #table.style = 'Light Grid Accent 1'

            table = document.add_table(rows=1, cols=2)
            # adjusted cell alignment here manually.
            hdr_cells = table.rows[0].cells
            hdr_cells[0].text = 'Confidence:'
            hdr_cells[0].width = Inches(.00)
            confidence = confidence.strip()
            hdr_cells[1].text = confidence
            hdr_cells[1].width = Inches(.5)
            hdr_cells[1].left_margin = .1
            row_cells = table.add_row().cells
            row_cells[0].text = 'Path:'
            row_cells[0].width = Inches(.00)
            path = path.strip()
            row_cells[1].text = path
            row_cells[1].width = Inches(.5)
            row_cells[1].left_margin = .1
            #table.style = 'Light Grid Accent 1'

            table = document.add_table(rows=1, cols=2)
            # adjusted cell alignment here manually.
            hdr_cells = table.rows[0].cells
            hdr_cells[0].text = 'IP:'
            hdr_cells[0].width = Inches(.00)
            ip = ip.strip()
            hdr_cells[1].text = ip
            hdr_cells[1].width = Inches(.5)
            hdr_cells[1].left_margin = .1
            row_cells = table.add_row().cells
            row_cells[0].text = 'Logged in As:'
            row_cells[0].width = Inches(.00)
            path = path.strip()
            row_cells[1].text = 'Development User'
            row_cells[1].width = Inches(.5)
            row_cells[1].left_margin = .1
Пример #2
0
def topimg(imgurl):
    response = requests.get(imgurl)
    img = BytesIO(response.content)
    document.add_picture(img, width=Inches(3), height=Inches(3))
    last_paragraph = document.paragraphs[-1]
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
Пример #3
0
#    {
#        "ingredient" : "Cu",
#        "content": 98
#   },
#  {
#     "ingredient" : "Fe",
#    "content": 2
#}
#]
#print(recordset[0]['id'])
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '成分'
hdr_cells[1].text = '含量'
for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item['ingredient'])
    row_cells[1].text = str(item['content'])

document.add_heading('输出数据', level=2)

fileadd = open("TTT_1.dat", "r")
contentadd = fileadd.read()
document.add_paragraph(contentadd)
fileadd.close()

graog_1 = document.add_picture('WeChat Screenshot_20201231153701.png',
                               width=Inches(2))

document.save('Pandat仿真报告.docx')
Пример #4
0
def writeLine(doc, line, end, notes, file):
    p = doc.add_paragraph()

    # Defines tab stops
    tab_stops = p.paragraph_format.tab_stops
    tab_stops.add_tab_stop(Inches(1.58), WD_TAB_ALIGNMENT.LEFT)

    # Defines relative font size based on song file
    class Size(Enum):
        NORMAL = auto()
        SMALL = auto()
        SMALL_LAST = auto()

    size = Size.NORMAL

    # Index variable for chord
    p, i = writeSection(p, line, "\t", 0)

    # Adds all chords
    lineLength = len(line)
    while i != lineLength:
        chord = line[i]
        iNext = True
        if chord == "|":
            run = p.add_run("|")
        elif chord == "new":
            run = p.add_run("\n")
        elif chord == "same":
            run = p.add_run("|  ")
            run, i = writeSection(p, line, "  ", i + 1)
            iNext = False
        elif chord[0] == "x" and len(chord) > 1 and chord[1:].isdecimal():
            run = p.add_run(f"x{chord[1:].lstrip('0')}")
        elif chord.count("/") == 1:
            chord = chord.split("/")
            run = p.add_run(f"{getChord(notes, chord[0], file)}/"
                            f"{getChord(notes, chord[1].upper(), file)}")
        elif chord[0] == "(" and chord[-1] == ")":
            run = p.add_run("(" + getChord(notes, chord[1:-1], file) + ")")
            size = Size.SMALL_LAST
        elif chord[0] == "(":
            run = p.add_run("(" + getChord(notes, chord[1:], file))
            size = Size.SMALL
        elif chord[-1] == ")":
            run = p.add_run(getChord(notes, chord[:-1], file) + ")")
            size = Size.SMALL_LAST
        else:
            run = p.add_run(getChord(notes, chord, file))

        # Set font size for small text
        if size in {Size.SMALL, Size.SMALL_LAST}:
            run.font.size = Pt(22)

        # Increments i if necessary
        if iNext:
            i += 1

        # Adds space after chord
        if i != lineLength:
            if chord == "new":
                run = p.add_run("\t")
            else:
                run = p.add_run("  ")

            # Set font size for small text
            if size == Size.SMALL:
                run.font.size = Pt(22)
            elif size == Size.SMALL_LAST:
                run.font.size = Pt(22)
                size = Size.NORMAL

    # Sets paragraph spacing
    if end:
        p.paragraph_format.space_after = Pt(10)
    else:
        p.paragraph_format.space_after = Pt(0)

    p.paragraph_format.space_before = Pt(0)
    p.paragraph_format.line_spacing = Pt(36)

    return doc
Пример #5
0
    def gen_docfile(df, pie_file_path, bar_file_path, doc_file_path):
        '''
        :param df_result: 数据记录,用于表格显示
        :param pie_file_path: 饼图文件显示
        :param bar_file_path: 柱状图文件显示
        :param doc_file_path: 需要保存的WORK文件路径
        :return: 无返回值
        '''
        # 新建一个文档
        document = Document()
        document.add_heading(u' 自动分析报告生成 ', 0)
        # 添加一个段落
        p = document.add_paragraph(
            u'python-doc模块是一个非常实用的用于自动生成报告的文档,可以自动根据读取的数据生成')
        p.add_run(u'图片').bold = True
        p.add_run(u' 和 ')
        p.add_run(u'表格').italic = True
        document.add_paragraph(u'python-doc模块可以用于:')
        #无序列表项
        document.add_paragraph(u'根据程序计算动态结果替换动态内容,如统计数字等', style='ListBullet')
        document.add_paragraph(u'可以自动嵌入相应的图片和表格', style='ListBullet')
        document.add_paragraph(u'支持各类样式进行调整', style='ListBullet')

        document.add_paragraph(u'python-doc模块不足的地方:')
        document.add_paragraph(u'相对简单', style='ListNumber')
        document.add_paragraph(u'暂不支持WORD文档模板', style='ListNumber')

        document.add_heading(u'二、各板块统计', level=1)
        text=u'沪深两地的上市A股总共有%s只,其中沪市有 %s 只,深市有%s 只,各板块的数据占比如下所示'\
             %(str(df['STOCKNAME'].count()),\
               str(df[df['TRDMARKETNAME']=='上海']['STOCKNAME'].count()),\
               str(df[df['TRDMARKETNAME']=='深圳']['STOCKNAME'].count())
               )
        document.add_paragraph(text)
        # 插入图片,文件名可以作为参数传入,由之前的程序进行传入
        document.add_picture(pie_file_path, width=Inches(5.0))

        document.add_heading(u'三、上市时间统计', level=1)
        text = u'\n上市时间分布图如下所示,可以看出今明两年并不上上市的高峰期'
        document.add_paragraph(text)
        # 插入图片,文件名可以作为参数传入,由之前的程序进行传入
        document.add_picture(bar_file_path, width=Inches(5.0))

        document.add_heading(u'四、待上市新股统计', level=1)
        # 轮询上市时间为空的未上市股票,添加表格
        text = u'\n待上市股票列表如下'
        df['TIMETOMARKET'] = df['TIMETOMARKET'].map(lambda x: '99991231'
                                                    if x is None else x[0:4])
        df_newstock = df[df['TIMETOMARKET'] == '99991231']
        print df_newstock
        #插入表格
        table = document.add_table(rows=len(df_newstock.index) + 1,
                                   cols=3,
                                   style='Table Grid')
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = u'股票名称'
        hdr_cells[1].text = u'上市交易所'
        hdr_cells[2].text = u'上市板块'
        #编历DATAFRAME
        list_stockname = list(df_newstock['STOCKNAME'])
        list_TRDMARKETNAME = list(df_newstock['TRDMARKETNAME'])
        list_PLATENAME = list(df_newstock['PLATENAME'])
        for i in range(len(df_newstock.index)):
            row_cells = table.add_row().cells
            #注意这里PYTHON2的编码问题,多谢stackoverflow,程序员的圣地
            row_cells[0].text = unicode(list_stockname[i], 'utf-8')
            row_cells[1].text = unicode(list_TRDMARKETNAME[i], 'utf-8')
            row_cells[2].text = unicode(list_PLATENAME[i], 'utf-8')

        document.add_page_break()
        document.save(doc_file_path)
Пример #6
0
    for table in tables:
        print("正在处理表:%s" % (table[0]))
        document.add_heading(
            "%s [%s] " % (table[0].decode('utf8'), table[1].decode('utf8')), 3)

        # 读取列信息
        columns = db.getColumn(table[0])
        table = document.add_table(1, cols=3)
        table.style = 'Table Grid'

        # 增加标题标题
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = u'名称'
        hdr_cells[1].text = u'类型'
        hdr_cells[2].text = u'备注'
        hdr_cells[2].width = Inches(4.25)

        # 增加表格数据
        for column in columns:
            row_cells = table.add_row().cells
            row_cells[0].text = column[0].decode('utf8')
            row_cells[1].text = column[1].decode('utf8')
            row_cells[2].text = column[2].decode('utf8')

        # 分页符
        document.add_page_break()

    # 保存文件
    try:
        document.save('db_document.docx')
    except:
Пример #7
0
def CreateTable(document,row, rsPicPath=None):
    rows,cols = 12,25
    table = document.add_table(rows=rows,cols=cols,style = 'Table Grid')
    table.alignment = WD_TABLE_ALIGNMENT.CENTER  # 表格整体居中
    table.style.font.size=Pt(11) # 字号
    for i in range(rows):
        table.rows[i].height = Cm(0.6)

    
    # 室内编号
    table.cell(0,0).merge(table.cell(0,2)).text=(u"解译编号")
    table.cell(0,3).merge(table.cell(0,6)).text=(row.getValue(u"解译编"))

    # 项目名称
    table.cell(0,7).merge(table.cell(0,11)).text=(u"子项目名称")
    table.cell(0,12).merge(table.cell(0,24)).text=(u'沿江规划区1:5万水文地质环境地质综合遥感解译')

    # 解译内容
    table.cell(1,0).merge(table.cell(2,2)).text=(u"解译内容")
    table.cell(1,3).merge(table.cell(2,8)).text=((u"断层"))
    table.cell(1,0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER

    #坐标
    table.cell(1,9).merge(table.cell(2,10)).text=(u"坐标")
    table.cell(1,9).vertical_alignment = WD_ALIGN_VERTICAL.CENTER

    # Y
    table.cell(2,11).merge(table.cell(2,12)).text=(u"Y")
    table.cell(2,13).merge(table.cell(2,16)).text=("{0:.2f}".format(row.getValue(u"Y坐标")))

    # X
    table.cell(1,11).merge(table.cell(1,12)).text=(u"X")
    table.cell(1,13).merge(table.cell(1,16)).text=("{0:.2f}".format(row.getValue(u"X坐标")))

    # N
    table.cell(1,17).merge(table.cell(1,18)).text=(u"N")
    table.cell(1,19).merge(table.cell(1,24)).text=(row.getValue(u"纬度"))

    # E
    table.cell(2,17).merge(table.cell(2,18)).text=(u"E")
    table.cell(2,19).merge(table.cell(2,24)).text=(row.getValue(u"经度"))

    # 地理位置
    table.cell(3,0).merge(table.cell(3,2)).text=(u'地理位置')
    table.cell(3,3).merge(table.cell(3,24)).text=(row.getValue(u'Problem'))
     
    # 影像概貌
    table.cell(4,0).merge(table.cell(4,2)).text=(u'影像概貌')
    table.cell(4,3).merge(table.cell(4,24)).text=(row.getValue(u'Problem'))

    # 遥感影像
    table.cell(5,0).merge(table.cell(5,2)).text=(u"遥感影像")
    table.cell(5,0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    c_polygonImage = table.cell(5,3).merge(table.cell(5,24))
    pic_p = c_polygonImage.paragraphs[0]
    pic_r = pic_p.add_run()
    pic_r.add_picture(rsPicPath,width=Inches(3))
    pic_p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    # 野外验证
    table.cell(6,0).merge(table.cell(6,2)).text=(u"野外验证")
    table.cell(6,0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    table.cell(6,3).merge(table.cell(6,13))
    table.cell(6,14).merge(table.cell(6,24))
    table.rows[6].height=Inches(3)

    # 综合解译
    table.cell(7,0).merge(table.cell(9,2)).text=(u'综合解译')
    table.cell(7,0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    table.cell(7,3).merge(table.cell(9,24)).text=(row.getValue(u'特征'))

    # 项目信息
    table.cell(10,0).merge(table.cell(10,2)).text=(u"项目名称")
    table.cell(10,3).merge(table.cell(10,15)).text=(u'宜昌市资源环境承载能力评价')
    table.cell(10,16).merge(table.cell(10,18)).text=(u"承担单位")
    table.cell(10,19).merge(table.cell(10,24)).text=(u'')

    # 人员信息
    table.cell(11,0).merge(table.cell(11,2)).text=(u"解译人员")
    table.cell(11,3).merge(table.cell(11,8)).text=(u'')
    table.cell(11,9).merge(table.cell(11,12)).text=(u"解译时间")
    table.cell(11,13).merge(table.cell(11,18)).text=('')
    table.cell(11,19).merge(table.cell(11,21)).text=(u'审核')
    table.cell(11,22).merge(table.cell(11,24)).text=('')
Пример #8
0
document = Document()

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph('first item in unordered list', style='ListBullet')
document.add_paragraph('first item in ordered list', style='ListNumber')

#urllib3.request.urlretrieve("http://placehold.it/350x150", "placeholder.png")
document.add_picture('monty-truth.png', width=Inches(1.25))

recordset = [
    {
        "id": 1,
        "qty": 2,
        "desc": "New item"
    },
    {
        "id": 2,
        "qty": 2,
        "desc": "New item"
    },
    {
        "id": 3,
        "qty": 2,
Пример #9
0
def evaluate_models(dict_models, Xs, ys, X_val_var, y_val_var, folds_index,
                    loss_metric, peeking_metrics, report_doc, add_plots,
                    report_dfs):
    y_probas = []
    for index, dict_model in enumerate(dict_models):
        y_probas.append(dict_model['model'].predict_proba(Xs[index])[:, 1])

    # Add a table for comparison of metrics
    if report_doc:
        report_doc.add_heading(f'Winner models of each fold and main metrics',
                               level=2)
        table = report_doc.add_table(rows=len(dict_models) + 1,
                                     cols=len(peeking_metrics) + 4)
        table.style = 'TableGrid'
        table.autofit = False
        # Fill first row of table
        first_row = table.rows[0]
        first_row.cells[0].width = Inches(SIZE_FOLD_COL)
        first_row.cells[0].paragraphs[0].add_run('Fold').bold = True
        first_row.cells[1].width = Inches(SIZE_MODEL_COL)
        first_row.cells[1].paragraphs[0].add_run('Model').bold = True
        first_row.cells[2].width = Inches(SIZE_PARAM_COL)
        first_row.cells[2].paragraphs[0].add_run('Params').bold = True
        first_row.cells[3].width = Inches(SIZE_COMMENT_COL)
        first_row.cells[3].paragraphs[0].add_run('Comments').bold = True
        for i, metric in enumerate(peeking_metrics):
            first_row.cells[i + 4].width = Inches(SIZE_METRIC_COL)
            first_row.cells[i + 4].paragraphs[0].add_run(metric).bold = True
        # Fill other rows of table
        metrics = []
        for index, dict_model in enumerate(dict_models):
            row_index = index + 1
            row = table.rows[row_index]
            row.cells[0].width = Inches(SIZE_FOLD_COL)
            row.cells[0].text = str(folds_index[index])
            row.cells[1].width = Inches(SIZE_MODEL_COL)
            row.cells[1].text = dict_model['params']['model']
            row.cells[2].width = Inches(SIZE_PARAM_COL)
            write_paragraphs_dict(row.cells[2], {
                key: value
                for (key, value) in dict_model['params'].items()
                if key != 'model'
            },
                                  SIZE_SMALL_FONT,
                                  is_cell_table=True)
            row.cells[3].width = Inches(SIZE_COMMENT_COL)
            write_paragraphs_dict(row.cells[3], {
                **{
                    'Type of model': type_of_model(dict_model['model'])
                },
                **dict_model['comments']
            },
                                  SIZE_SMALL_FONT,
                                  is_cell_table=True)
            for i, metric in enumerate(peeking_metrics):
                row.cells[i + 4].width = Inches(SIZE_METRIC_COL)
                value_of_metric = get_metric(metric, 'real')(ys[index],
                                                             y_probas[index])
                if metric == loss_metric:
                    metrics.append(value_of_metric)
                row.cells[i + 4].paragraphs[0].add_run(
                    str(np.round(value_of_metric, 3)))
        # Add average
        report_doc.add_paragraph(
            f'For the selected optimization metric {loss_metric} '
            f'the average score is {np.round(np.mean(metrics), 3)}'
            f', and the standard deviation is {np.round(np.std(metrics), 3)}.')

    if add_plots and report_doc:
        add_plots_doc(report_doc, ys, y_probas, folds_index)

    if len(y_val_var) > 0 and report_doc:
        report_doc.add_heading(
            'Comparison of several predictions to assess variance', level=2)
        table = report_doc.add_table(rows=len(y_val_var) + 1,
                                     cols=len(dict_models) + 3)
        table.style = 'TableGrid'
        table.autofit = False
        # Fill first row of table
        first_row = table.rows[0]
        first_row.cells[0].width = Inches(SIZE_FOLD_COL)
        first_row.cells[0].paragraphs[0].add_run('Instance').bold = True
        first_row.cells[1].width = Inches(SIZE_FOLD_COL)
        first_row.cells[1].paragraphs[0].add_run('Real label').bold = True
        for i in range(len(dict_models)):
            first_row.cells[i + 2].width = Inches(SIZE_METRIC_COL)
            first_row.cells[i + 2].paragraphs[0].add_run(
                f'Prediction by model of fold {folds_index[i]}').bold = True
        first_row.cells[len(dict_models) + 2].width = Inches(SIZE_METRIC_COL)
        first_row.cells[len(dict_models) + 2].paragraphs[0].add_run(
            'Standard deviation in predictions of this instance').bold = True
        # Fill other rows
        stds = []
        for index, y in enumerate(y_val_var):
            predictions = []
            row_index = index + 1
            row = table.rows[row_index]
            row.cells[0].width = Inches(SIZE_FOLD_COL)
            row.cells[0].paragraphs[0].add_run(str(row_index))
            row.cells[1].width = Inches(SIZE_FOLD_COL)
            row.cells[1].paragraphs[0].add_run(str(y))
            for i, dict_model in enumerate(dict_models):
                row.cells[i + 2].width = Inches(SIZE_METRIC_COL)
                prediction = dict_model['model'].predict_proba(
                    X_val_var[[index]])[:, 1]
                predictions.append(prediction)
                row.cells[i + 2].paragraphs[0].add_run(
                    str(np.round(prediction[0], 3)))
            row.cells[len(dict_models) + 2].width = Inches(SIZE_METRIC_COL)
            std = np.std(predictions)
            stds.append(std)
            row.cells[len(dict_models) + 2].paragraphs[0].add_run(
                str(np.round(std, 3)))
        report_doc.add_paragraph(
            f'The average standard deviation is {np.round(np.mean(stds),3)}')
    if report_doc:
        plots_report_dfs(report_doc, report_dfs, loss_metric)
    return
    def __init__(self, chrome_path, folder_path):
        self.chrome = chrome_path
        self.path = folder_path

        from selenium import webdriver
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.common.exceptions import TimeoutException
        from selenium.webdriver.common.keys import Keys
        from docx import Document
        from docx.shared import Inches, Pt
        from docx.enum.text import WD_ALIGN_PARAGRAPH
        from datetime import date
        from docx.shared import RGBColor
        import pandas as pd
        import sys
        import random
        import string
        try:
            self.out_passed = True
            testdata_path = self.path + '\\' + '2_testcase.xlsx'
            Testdata = pd.read_excel(testdata_path)
            Step = 0
            today = date.today()
            d4 = today.strftime("%b-%d-%Y")
            d3 = today.strftime("%b_%d_%Y")
            document = Document()
            p = document.add_paragraph()
            p.alignment = WD_ALIGN_PARAGRAPH.CENTER
            title = p.add_run("2_testcase")
            title.bold = True
            title.font.size = Pt(16)
            Para1 = document.add_paragraph()
            title1 = Para1.add_run(d4)
            title1.bold = True
            title1.font.size = Pt(12)
            title1.font.color.rgb = RGBColor(128, 0, 0)
            PathChrome = self.chrome
            driver = webdriver.Chrome(PathChrome)
            driver.get(" https://www.sogeti.com/")
            driver.maximize_window()
            WebDriverWait(driver, 20).until(
                EC.visibility_of_element_located((
                    By.XPATH,
                    '//*[@id="header"]/div[1]/nav[1]/ul[1]/li[3]/div[1]/span[1]'
                )))
            document.add_paragraph(Testdata.at[Step, 'Describtion'])
            document.add_paragraph('Passed')
            driver.save_screenshot(self.path + '\\' + 'pic.jpg')
            document.add_picture(self.path + '\\' + 'pic.jpg', width=Inches(7))
            Step = Step + 1
            driver.find_element_by_xpath(
                '//*[@id="header"]/div[1]/nav[1]/ul[1]/li[3]/div[1]/span[1]'
            ).click()
            WebDriverWait(driver, 20).until(
                EC.visibility_of_element_located(
                    (By.XPATH,
                     '//*[@id="header"]/div[1]/div[5]/ul[1]/li[7]/a[1]')))
            driver.find_element_by_xpath(
                '//*[@id="header"]/div[1]/div[5]/ul[1]/li[7]/a[1]').click()
            WebDriverWait(driver, 20).until(
                EC.visibility_of_element_located((
                    By.XPATH,
                    '//*[@id="primary_content"]/div[1]/div[2]/div[1]/h1[1]/span[1]'
                )))
            r_name1 = ''
            r_name2 = ''
            r_number = ''
            for x in range(6):
                r_name1 = r_name1 + random.choice(string.ascii_letters)
            driver.find_element_by_xpath(
                '//*[@id="4ff2ed4d-4861-4914-86eb-87dfa65876d8"]').send_keys(
                    r_name1)
            for x in range(6):
                r_name2 = r_name2 + random.choice(string.ascii_letters)
            driver.find_element_by_xpath(
                '//*[@id="11ce8b49-5298-491a-aebe-d0900d6f49a7"]').send_keys(
                    r_name2)

            driver.find_element_by_xpath(
                '//*[@id="056d8435-4d06-44f3-896a-d7b0bf4d37b2"]').send_keys(
                    r_name1 + '.' + r_name2 + '@rrr.com')
            for x in range(8):
                r_number = r_number + str(random.randint(0, 9))
            driver.find_element_by_xpath(
                '//*[@id="755aa064-7be2-432b-b8a2-805b5f4f9384"]').send_keys(
                    r_number)
            driver.find_element_by_xpath(
                '//*[@id="88459d00-b812-459a-99e4-5dc6eff2aa19"]').send_keys(
                    'Hello ' + r_name1 + ' ' + ' ' + r_name2)
            driver.find_element_by_xpath('//*[@value="I agree"]').click()
            document.add_paragraph(Testdata.at[Step, 'Describtion'])
            document.add_paragraph('Passed')
            driver.save_screenshot(self.path + '\\' + 'pic.jpg')
            document.add_picture(self.path + '\\' + 'pic.jpg', width=Inches(7))
            Step = Step + 1
            driver.find_element_by_xpath('//*[@name="submit"]').click()
            WebDriverWait(driver, 20).until(
                EC.visibility_of_element_located((
                    By.XPATH,
                    '//*[@class="Form__Status__Message Form__Success__Message"]'
                )))
            message = driver.find_element_by_xpath(
                '//*[@class="Form__Status__Message Form__Success__Message"]'
            ).text
            if (message == 'Thank you for contacting us.'):
                document.add_paragraph(Testdata.at[Step, 'Describtion'])
                document.add_paragraph('Passed')
                driver.save_screenshot(self.path + '\\' + 'pic.jpg')
                document.add_picture(self.path + '\\' + 'pic.jpg',
                                     width=Inches(7))
                Step = Step + 1
            else:
                document.add_paragraph(Testdata.at[Step, 'Describtion'])
                document.add_paragraph('Failed:Wrong Titel')
                driver.save_screenshot(self.path + '\\' + 'pic.jpg')
                document.add_picture(self.path + '\\' + 'pic.jpg',
                                     width=Inches(7))
                raise Exception("BusinessError:wronge message")

        except:
            document.add_paragraph('sys.exc_info()')
            driver.save_screenshot(self.path + '\\' + 'pic.jpg')
            self.out_passed = False
        finally:
            docName = self.path + '\\' + '2_testcase' + '_' + d3 + '.docx'
            document.save(docName)
            self.report_path = docName
            self.report = [self.out_passed, self.report_path]
            driver.quit()
Пример #11
0
#设置粗体
run = paragraph.add_run(u'粗体').bold = True

#增加引用
document.add_paragraph('Intense quote', style='Intense Quote')

#增加有序列表
document.add_paragraph(u'有序列表元素1', style='List Number')
document.add_paragraph(u'有序列别元素2', style='List Number')

#增加无序列表
document.add_paragraph(u'无序列表元素1', style='List Bullet')
document.add_paragraph(u'无序列表元素2', style='List Bullet')

#增加图片(此处使用相对位置)
document.add_picture('jdb.jpg', width=Inches(1.25))

#增加表格
table = document.add_table(rows=3, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = "第一列"
hdr_cells[1].text = "第二列"
hdr_cells[2].text = "第三列"

hdr_cells = table.rows[1].cells
hdr_cells[0].text = '2'
hdr_cells[1].text = 'aerszvfdgx'
hdr_cells[2].text = 'abdzfgxfdf'

hdr_cells = table.rows[2].cells
hdr_cells[0].text = '3'
Пример #12
0
from docx import Document 
from docx.shared import Inches

document = Document()

# profile picture
document.add_picture(
    'profile.jpg', 
    width =Inches(2.0))


# name phone number and details
name = input('What is your name? ')
phone_number = input('What is your phone number? ')
email = input('What is your email? ')

document.add_paragraph(
     name + ' | ' + phone_number + ' | ' + email)

#about me
document.add_heading('About me')
document.add_paragraph(input('Tell about yourself? '))

# work expreience
document.add_heading('Work Experience')
p = document.add_paragraph()

company = input('Enter company ')
from_date = input('From Date ')
to_date = input('To Date ')
Пример #13
0
def fetch(entries, root, i):
    l = []  #creates an empty list
    for entry in entries:  #iterates over the list of values received from the form
        field = entry[0]
        text = entry[1].get()
        l.append(text)  #appends the values of each field in a list.
    root.destroy()
    document.add_picture(
        image, width=Inches(2.25))  #inserts the image in the doc file.
    document.add_paragraph("Personal Information: ", style="Intense Quote"
                           )  #inserts user's personal details in the doc file
    document.add_paragraph("Name :   ").add_run(l[0])
    document.add_paragraph("D.O.B :   ").add_run(l[1])
    document.add_paragraph("Nationality :   ").add_run(l[2])
    document.add_paragraph("Objective : ",
                           style="Intense Quote")  #displays user's objective
    document.add_paragraph(
        "To acquire valuable knowledge and skills to complement that I have learnt from school in an actual job environment."
    )
    document.add_paragraph(
        "In return, I offer my service and determination to be an asset to your company throughout the duration of my training period."
    )
    document.add_paragraph('Educational Qualifications: ',
                           style="Intense Quote"
                           )  #inserts user's educational info. in the doc file
    document.add_paragraph("School :   ").add_run(l[5])
    document.add_paragraph("Duration :   ").add_run(l[6])
    document.add_paragraph().add_run("Degree :   " + l[9])
    document.add_paragraph("College/University :   ").add_run(l[7])
    document.add_paragraph("Duration :   ").add_run(l[8])
    document.add_paragraph(
        'Skills: ', style="Intense Quote"
    )  #inserts user's skills and interests in the doc file
    document.add_paragraph("Interests :   ",
                           style='List Bullet').add_run().bold = True
    document.add_paragraph("--> " + l[10])
    document.add_paragraph("Computer Languages Known :   ",
                           style='List Bullet').add_run().bold = True
    document.add_paragraph("--> " + l[11])
    document.add_paragraph(
        "Work Experience: ",
        style="Intense Quote")  #inserts user's work experience
    document.add_paragraph('1. ',
                           style='List Bullet').add_run(l[12] + ' ( ' + l[13] +
                                                        ' )').bold = True
    document.add_paragraph("Duration :   ").add_run(l[14])
    document.add_paragraph('2. ',
                           style='List Bullet').add_run(l[15] + ' ( ' + l[16] +
                                                        ' )').bold = True
    document.add_paragraph("Duration :   ").add_run(l[17])

    document.add_paragraph("Contact Details: ", style="Intense Quote"
                           )  #displays user's contact details in the doc file
    document.add_paragraph("Mobile:  ").add_run(l[3])
    document.add_paragraph("Email:  ").add_run(l[4])
    if i == 1:
        document.save(l[0] + '_CV' + '.docx')  #creates CV in .doc format
    else:
        document.save(l[0] + '_CV' + '.docx')
        wdFormatPDF = 17
        in_file = os.path.abspath(l[0] + '_CV' + '.docx')
        out_file = os.path.abspath(
            l[0] + '_CV' +
            '.pdf')  #creates CV in .pdf format as per user's choice

        word = comtypes.client.CreateObject('Word.Application')
        doc = word.Documents.Open(in_file)
        doc.SaveAs(
            out_file, FileFormat=wdFormatPDF
        )  #saves the pdf with the file name consisting of user's name.
        doc.Close()
        word.Quit()

    print "CV Created"
    dic_result = client.basicGeneral(image)
    res = dic_result['words_result']
    result = ''
    r = 1
    for m in res:
        # print(str(m['words']))
        result = result + str(m['words'])
        if r == 1:
            result += "\n"
        r += 1
    return result


doc = Document("template.docx")
doc.save(name + '.docx')
for i in range(len(os.listdir(path))):
    doc = Document(name + '.docx')
    index = path + "/ (%i).png" % (i + 1)
    getresult = image2text(index)

    # to delete the whatnot info that prohibit python-docx insert image
    f = Image.open(index)  #你的图片文件
    f.save(index)  #替换掉你的图片文件
    f.close()

    doc.add_picture(index, width=Inches(6))
    paragraph = doc.add_paragraph(getresult)
    doc.save(name + '.docx')

    print('页面' + str(i) + '已完成')
def make_document(file, log):
    """Produce Word Document transcriptions using the automatic speech recognition from AWS Transcribe."""

    # Initiate Document
    document = Document()
    # A4 Size
    document.sections[0].page_width = Mm(210)
    document.sections[0].page_height = Mm(297)
    # Font
    font = document.styles['Normal'].font
    font.name = 'Calibri'

    # Load Transcription output from command line input
    # eg: python3 application.py 'output.json'
    data = json.load(open(file))
    click.echo(f"{click.format_filename(file)} opened...")

    # Document title and intro
    title = f"Transcription of {data['jobName']}"
    document.add_heading(title, level=1)
    # Set thresholds for formatting later
    threshold_for_grey = 0.98
    # Intro
    document.add_paragraph(
        'Transcription using AWS Transcribe automatic speech recognition.')
    document.add_paragraph(datetime.datetime.now().strftime(
        'Document produced on %A %d %B %Y at %X.'))
    document.add_paragraph()  # Spacing
    document.add_paragraph(
        f"Grey text has less than {int(threshold_for_grey * 100)}% confidence."
    )

    # Stats dictionary
    stats = {
        'timestamps': [],
        'accuracy': [],
        '9.8': 0,
        '9': 0,
        '8': 0,
        '7': 0,
        '6': 0,
        '5': 0,
        '4': 0,
        '3': 0,
        '2': 0,
        '1': 0,
        '0': 0,
        'total': len(data['results']['items'])
    }

    # Confidence count

    click.echo('Producing stats...')
    for item in data['results']['items']:
        if item['type'] == 'pronunciation':
            stats['timestamps'].append(float(item['start_time']))
            stats['accuracy'].append(
                int(float(item['alternatives'][0]['confidence']) * 100))
            if float(item['alternatives'][0]['confidence']) >= 0.98:
                stats['9.8'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.9:
                stats['9'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.8:
                stats['8'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.7:
                stats['7'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.6:
                stats['6'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.5:
                stats['5'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.4:
                stats['4'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.3:
                stats['3'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.2:
                stats['2'] += 1
            elif float(item['alternatives'][0]['confidence']) >= 0.1:
                stats['1'] += 1
            else:
                stats['0'] += 1
    # Display confidence count table
    table = document.add_table(rows=1, cols=3)
    table.style = document.styles['Light List Accent 1']
    table.alignment = WD_ALIGN_PARAGRAPH.CENTER
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Confidence'
    hdr_cells[1].text = 'Count'
    hdr_cells[2].text = 'Percentage'
    row_cells = table.add_row().cells
    row_cells[0].text = str('98% - 100%')
    row_cells[1].text = str(stats['9.8'])
    row_cells[2].text = str(round(stats['9.8'] / stats['total'] * 100,
                                  2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('90% - 97%')
    row_cells[1].text = str(stats['9'])
    row_cells[2].text = str(round(stats['9'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('80% - 89%')
    row_cells[1].text = str(stats['8'])
    row_cells[2].text = str(round(stats['8'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('70% - 79%')
    row_cells[1].text = str(stats['7'])
    row_cells[2].text = str(round(stats['7'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('60% - 69%')
    row_cells[1].text = str(stats['6'])
    row_cells[2].text = str(round(stats['6'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('50% - 59%')
    row_cells[1].text = str(stats['5'])
    row_cells[2].text = str(round(stats['5'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('40% - 49%')
    row_cells[1].text = str(stats['4'])
    row_cells[2].text = str(round(stats['4'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('30% - 39%')
    row_cells[1].text = str(stats['3'])
    row_cells[2].text = str(round(stats['3'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('20% - 29%')
    row_cells[1].text = str(stats['2'])
    row_cells[2].text = str(round(stats['2'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('10% - 19%')
    row_cells[1].text = str(stats['1'])
    row_cells[2].text = str(round(stats['1'] / stats['total'] * 100, 2)) + '%'
    row_cells = table.add_row().cells
    row_cells[0].text = str('0% - 9%')
    row_cells[1].text = str(stats['0'])
    row_cells[2].text = str(round(stats['0'] / stats['total'] * 100, 2)) + '%'
    # Add paragraph for spacing
    document.add_paragraph()
    # Display scatter graph of confidence
    # Confidence of each word as scatter graph
    plt.scatter(stats['timestamps'], stats['accuracy'])
    # Mean average as line across graph
    plt.plot([stats['timestamps'][0], stats['timestamps'][-1]], [
        statistics.mean(stats['accuracy']),
        statistics.mean(stats['accuracy'])
    ], 'r')
    # Formatting
    plt.xlabel('Time (seconds)')
    # plt.xticks(range(0, int(stats['timestamps'][-1]), 60))
    plt.ylabel('Accuracy (percent)')
    plt.yticks(range(0, 101, 10))
    plt.title('Accuracy during video')
    plt.legend(['Accuracy average (mean)', 'Individual words'],
               loc='lower center')
    plt.savefig('chart.png')
    document.add_picture('chart.png', width=Cm(14.64))
    document.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER
    document.add_page_break()

    # Process and display transcript by speaker segments
    click.echo('Writing transcript...')
    table = document.add_table(rows=1, cols=3)
    table.style = document.styles['Light List Accent 1']
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Time'
    hdr_cells[1].text = 'Speaker'
    hdr_cells[2].text = 'Content'

    with click.progressbar(
            data['results']['speaker_labels']['segments']) as bar:
        for segment in bar:
            # If there is content in the segment
            if len(segment['items']) > 0:
                # Add a row, write the time and speaker
                row_cells = table.add_row().cells
                row_cells[0].text = convert_time_stamp(segment['start_time'])
                row_cells[1].text = str(segment['speaker_label'])

                # Segments group individual word results by speaker. They are cross-referenced by time.
                # For each word in the segment...
                for word in segment['items']:
                    # Run through the word results and get the corresponding result
                    for result in data['results']['items']:
                        if result['type'] == 'pronunciation':
                            if result['start_time'] == word['start_time']:

                                # Get the word with the highest confidence
                                if len(result['alternatives']) > 0:
                                    current_word = dict()
                                    confidence_scores = []
                                    for score in result['alternatives']:
                                        confidence_scores.append(
                                            score['confidence'])
                                    for alternative in result['alternatives']:
                                        if alternative['confidence'] == max(
                                                confidence_scores):
                                            current_word = alternative.copy()

                                    # Write and format the word
                                    run = row_cells[2].paragraphs[0].add_run(
                                        ' ' + current_word['content'])
                                    if float(current_word['confidence']
                                             ) < threshold_for_grey:
                                        font = run.font
                                        font.color.rgb = RGBColor(
                                            204, 204, 204)

                                    # If the next item is punctuation, add it
                                    try:
                                        if data['results']['items'][
                                                data['results']['items'].index(
                                                    result) +
                                                1]['type'] == 'punctuation':
                                            run = row_cells[2].paragraphs[
                                                0].add_run(
                                                    data['results']['items']
                                                    [data['results']
                                                     ['items'].index(result) +
                                                     1]['alternatives'][0]
                                                    ['content'])
                                    # Occasional IndexErrors encountered
                                    except:
                                        pass

    # Formatting transcript table widthds
    click.echo('Formatting...')
    widths = (Inches(0.6), Inches(1), Inches(4.5))
    with click.progressbar(table.rows) as bar:
        for row in bar:
            for idx, width in enumerate(widths):
                row.cells[idx].width = width

    # Save the file
    document_title = f"{data['jobName']}.docx"
    document.save(document_title)
    click.echo(f"{document_title} saved.")

    if log:
        # Logging
        logs = boto3.client(
            'logs'
        )  # this might throw exception if we don't have `aws configure`

        def write_log(log_text):
            log_info = logs.describe_log_streams(logGroupName=log[0],
                                                 logStreamNamePrefix=log[1])
            log_time = int(datetime.datetime.now().timestamp() * 1000)
            response = logs.put_log_events(
                logGroupName=log[0],
                logStreamName=log[1],
                logEvents=[
                    {
                        'timestamp': log_time,
                        'message': log_text
                    },
                ],
                sequenceToken=log_info['logStreams'][0]['uploadSequenceToken'])

        job_finish = datetime.datetime.now()
        job_duration = job_finish - job_start
        write_log(
            f"Job name: {data['jobName']}, Word count: {stats['total']}, Accuracy average: {round(statistics.mean(stats['accuracy']), 2)}, Job duration: {job_duration.seconds}"
        )
        click.echo(f"{data['jobName']} logged.")
Пример #16
0
def write_train_report(report_doc, list_params, list_metrics,
                       list_holdout_metrics, peeking_metrics, list_comments):
    print_holdout_metrics = len(list_holdout_metrics) > 0
    list_loss_metrics = [metric['loss_metric'] for metric in list_metrics]
    index_best_model = list_loss_metrics.index(min(list_loss_metrics))
    report_doc.add_paragraph(
        f'Best model with respect to selected metric is {list_params[index_best_model]["model"]} with the following params:'
    )
    write_paragraphs_dict(
        report_doc, {
            key: value
            for (key, value) in list_params[index_best_model].items()
            if key != 'model'
        })

    report_doc.add_heading(
        f'Comparison of all models trained in this outer fold', level=3)
    # Create table for comparison
    if print_holdout_metrics:
        table = report_doc.add_table(rows=len(list_params) + 1,
                                     cols=len(peeking_metrics) * 2 + 3)
    else:
        table = report_doc.add_table(rows=len(list_params) + 1,
                                     cols=len(peeking_metrics) + 3)
    table.style = 'TableGrid'
    table.autofit = False
    # Fill first row of table
    first_row = table.rows[0]
    first_row.cells[0].width = Inches(SIZE_MODEL_COL)
    first_row.cells[0].paragraphs[0].add_run('Model').bold = True
    first_row.cells[1].width = Inches(SIZE_PARAM_COL)
    first_row.cells[1].paragraphs[0].add_run('Params').bold = True
    first_row.cells[2].width = Inches(SIZE_COMMENT_COL)
    first_row.cells[2].paragraphs[0].add_run('Comments').bold = True
    for i, metric in enumerate(peeking_metrics):
        first_row.cells[i + 3].width = Inches(SIZE_METRIC_COL)
        first_row.cells[i +
                        3].paragraphs[0].add_run(metric +
                                                 ' on inner fold').bold = True
    if print_holdout_metrics:
        for i, metric in enumerate(peeking_metrics):
            first_row.cells[i + 3 + len(peeking_metrics)].width = Inches(
                SIZE_METRIC_COL)
            first_row.cells[i + 3 +
                            len(peeking_metrics)].paragraphs[0].add_run(
                                metric + ' on outer fold').bold = True
    # Fill other rows
    for row_index, params in enumerate(list_params):
        row = table.rows[row_index + 1]
        if index_best_model == row_index:
            color_row(row)
        row.cells[0].width = Inches(SIZE_MODEL_COL)
        row.cells[0].text = params['model']
        row.cells[1].width = Inches(SIZE_PARAM_COL)
        write_paragraphs_dict(row.cells[1], {
            key: value
            for (key, value) in list_params[row_index].items()
            if key != 'model'
        },
                              SIZE_SMALL_FONT,
                              is_cell_table=True)
        row.cells[2].width = Inches(SIZE_COMMENT_COL)
        write_paragraphs_dict(row.cells[2],
                              list_comments[row_index],
                              SIZE_SMALL_FONT,
                              is_cell_table=True)
        for i, metric in enumerate(peeking_metrics):
            row.cells[i + 3].width = Inches(SIZE_METRIC_COL)
            row.cells[i + 3].text = str(
                np.round(list_metrics[row_index]['peeking_metrics'][metric],
                         3))
        if print_holdout_metrics:
            for i, metric in enumerate(peeking_metrics):
                row.cells[i + 3 +
                          len(peeking_metrics)].width = Inches(SIZE_METRIC_COL)
                row.cells[i + 3 + len(peeking_metrics)].text = str(
                    np.round(
                        list_holdout_metrics[row_index]['peeking_metrics']
                        [metric], 3))
    return
Пример #17
0
document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph('first item in unordered list', style='List Bullet')
document.add_paragraph('first item in ordered list', style='List Number')

document.add_picture('demo-docx.png', width=Inches(1.25))

records = ((3, '101', 'Spam'), (7, '422', 'Eggs'),
           (4, '631', 'Spam, spam, eggs, and spam'))

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc
Пример #18
0
# 3、设置字体格式
p.add_run('我是加粗、黑体').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('我是一级标题', level=1)
document.add_paragraph('我是自然段2', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
    '我是数字序号', style='List Number'
)
# 4、在指定位置添加图片
document.add_picture('demo.jpg', width=Inches(5))

records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)
# 5、在指定位置添加表格
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '我是第1列'
hdr_cells[1].text = '我是第2列'
hdr_cells[2].text = '我是第3列'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
elem = driver.find_element_by_id("CustomerGroup_description")
elem.send_keys("This is description for School number " + str(count + 1) +
               ", added for testing.")

# select parent_
select = Select(driver.find_element_by_id("CustomerGroup_parent_id"))
select.select_by_index(count - 3)
selected = select.first_selected_option.text
print('selected', selected)

### Screenshot of selected parent
driver.fullscreen_window()
driver.implicitly_wait(5)
driver.save_screenshot('selected_parent.png')
driver.maximize_window()
document.add_picture('selected_parent.png', width=Inches(6.25))

elem = driver.find_element_by_id("save-button")
#elem.click()   ####CHANGE HERE
driver.get("https://cinq.repairq.io/customerGroups/15")

driver.implicitly_wait(5)

### Screenshot of summary page, after save
driver.fullscreen_window()
driver.implicitly_wait(5)
driver.save_screenshot('created_customer_group.png')
driver.maximize_window()
document.add_picture('created_customer_group.png', width=Inches(6.25))

d = datetime.datetime.now()
Пример #20
0
document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph('first item in unordered list', style='ListBullet')
document.add_paragraph('first item in ordered list', style='ListNumber')

document.add_picture('0_0.bmp', width=Inches(1.25))

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item.qty)
    row_cells[1].text = str(item.id)
    row_cells[2].text = item.desc

document.add_page_break()

document.save('demo.docx')
today = time.strftime("%y{y}%m{m}%d{d}", time.localtime()).format(y='年',
                                                                  m='月',
                                                                  d='日')
company_list = [
    '客户1',
    '客户2',
    '客户3',
]

for i in company_list:
    document = Document()
    document.styles["Normal"].font.name = u'宋体'  #设置文档默认字体为宋体
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'),
                                                      u'宋体')  #设置中文字体

    document.add_picture('b.jpg', width=Inches(6))  #添加图片,Inches设置图片大小

    #设置第一自然段内容
    p1 = document.add_paragraph()  #初始化自然段
    p1.alignment = WD_ALIGN_PARAGRAPH.CENTER  #对齐设置成居中,默认为左对齐
    run1 = p1.add_run('关于下达%s的通知' % (today))
    run1.font.name = '微软雅黑'  #设置段落字体
    run1._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    run1.font.size = Pt(21)  #设置字体大小
    run1.font.bold = True  #设置加粗
    p1.space_after = Pt(5)  #段后距离5磅
    p1.space_before = Pt(5)  #段前距离5磅

    #添加表格
    table = document.add_table(
        rows=3, cols=3, style='Table Grid')  #初始化一个表格,3行3列,表格类型为Table Grid
Пример #22
0
#!/usr/bin/env python 
# -*- coding:utf-8 -*-
from docx import Document
from docx.shared import Inches

if __name__ == '__main__':
    document_ins = Document()
    document_ins.add_heading('Document Title', 0)

    document_ins.add_picture('pic_for_word.jpg', width=Inches(6))

    records = (
        (3, '101', 'Spam'),
        (7, '422', 'Eggs'),
        (4, '631', 'Spam, spam, eggs, and spam')
    )

    table = document_ins.add_table(rows=1, cols=3, style='Light Grid Accent 2')

    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Qty'
    hdr_cells[1].text = 'Id'
    hdr_cells[2].text = 'Desc'
    for qty, id, desc in records:
        row_cells = table.add_row().cells
        row_cells[0].text = str(qty)
        row_cells[1].text = id
        row_cells[2].text = desc
        pass
    document_ins.save('demo.docx')
Пример #23
0
def generarDocx():
    filename = direccion.cget("text")
    documentoExcel = openpyxl.load_workbook(filename)
    hojaActiva = documentoExcel.active
    i = 1
    while hojaActiva.cell(row=i, column=4).value != nombre_alumno.get():
        i += 1
        if i > hojaActiva.max_row:
            break
    if i > hojaActiva.max_row:
        find = "Alumno no encontrado"
    else:
        find = hojaActiva.cell(row=i, column=4).value
    fila = i

    nombrepdf = nombre_alumno.get()
    listanombrepdf = nombrepdf.split(' ')

    nombrepdf = ""

    for elemento in listanombrepdf:
        nombrepdf += elemento
    nombrepdf += "_reporte.docx"

    document = Document()
    document.add_heading(
        "Resultados: " + nombre_alumno.get() + "\nEdad; " +
        str(int(hojaActiva.cell(row=i, column=3).value)) + " años. Género; " +
        hojaActiva.cell(row=i, column=2).value + ". Localidad; " +
        hojaActiva.cell(row=i, column=148).value, 1)
    p1 = document.add_paragraph()
    p1.add_run('Árbol de la Vida:').bold = True

    for x in range(0, 7):
        p2 = document.add_paragraph()
        p2.add_run(hojaActiva.cell(row=1, column=5 + x).value).italic = True
        p3 = document.add_paragraph(hojaActiva.cell(row=i, column=5 + x).value)
    p4 = document.add_paragraph()
    p4.add_run("Razones para estudiar una carrera universitaria:").bold = True
    respuestasRazones = hojaActiva.cell(row=i, column=12).value.split('\n')
    for x in range(0, 4):
        p5 = document.add_paragraph(respuestasRazones[x])
    p6 = document.add_paragraph()
    p6.add_run('De niño deseaba ser:').bold = True
    p7 = document.add_paragraph()
    p7.add_run(hojaActiva.cell(row=i, column=13).value).italic = True
    document.add_page_break()
    p8 = document.add_paragraph()
    p8.add_run("Eligió las siguientes personalidades:").bold = True
    for x in range(0, 4):
        p9 = document.add_paragraph(
            hojaActiva.cell(row=i, column=14 + x).value)
    p10 = document.add_paragraph()
    p10.add_run("Preguntas Finales:").bold = True

    for x in range(0, 10):
        p11 = document.add_paragraph()
        p11.add_run(hojaActiva.cell(row=1,
                                    column=18 + x).value[:-24]).italic = True
        valorSeparado = hojaActiva.cell(row=i, column=18 + x).value.split('\n')
        p11 = document.add_paragraph(valorSeparado[0] + ", " +
                                     valorSeparado[1])
    table = document.add_table(rows=12, cols=2)

    table.cell(0, 0).text = "-----RESPUESTAS INVENTARIO-----"
    table.cell(1, 0).text = "INTERESES:"
    table.cell(1, 1).text = "APTITUDES:"

    row = table.rows[2]
    printInventario(ss_intereses, ss_aptitudes, row)
    row = table.rows[3]
    printInventario(ep_intereses, ep_aptitudes, row)
    row = table.rows[4]
    printInventario(v_intereses, v_aptitudes, row)
    row = table.rows[5]
    printInventario(ap_intereses, ap_aptitudes, row)
    row = table.rows[6]
    printInventario(m_intereses, m_aptitudes, row)
    row = table.rows[7]
    printInventario(o_intereses, o_aptitudes, row)
    row = table.rows[8]
    printInventario(cient_intereses, cient_aptitudes, row)
    row = table.rows[9]
    printInventario(calc_intereses, calc_aptitudes, row)
    row = table.rows[10]
    printInventario(mc_intereses, mc_aptitudes, row)
    row = table.rows[11]
    printInventario(al_intereses, dm_aptitudes, row)
    p14 = document.add_paragraph()
    p14.alignment = 1
    r14 = p14.add_run()
    r14.add_picture(nombre_alumno.get() + '_grafica.jpg', width=Inches(7.5))

    document.save(nombrepdf)
    os.remove(nombre_alumno.get() + '_grafica.jpg')
    os.startfile(nombrepdf)
Пример #24
0
from docx import Document
from docx.shared import Inches

document = Document()
# Profile Picture
document.add_picture('profile.png', width=Inches(1.5))
#Basic Information Like Name, Phone Number and Email
name = input("What is your full Name?")
phone_number = input("What is your Phone Number?")
email = input("What is your Email?")

# Heading Title
document.add_heading(name, 0)

document.add_paragraph(phone_number + ' | ' + email)

# About Me Section
document.add_heading('Objective', 0)
about_me = input('Write your Objective? ')
document.add_paragraph(about_me)

# Work Experience Section
document.add_heading('Work Experience', 0)
para = document.add_paragraph()

no_of_experiences = int(
    input("How many Employers' Experience do you want to add "))
# 4

for i in range(no_of_experiences):
    company = input("Enter your Company? ")
Пример #25
0
import docx
from docx.shared import Inches, Cm

doc = docx.Document()
doc.add_paragraph('This is on the first page!')
# 要添加换行符(而不是开始一个新的段落),可以在 Run 对象上调用 add_break()方法,
# 换行符将出现在它后面。如果希望添加换页符,可以将 docx.text.WD_BREAK.PAGE
# 作为唯一的参数,传递给 add_break(),就像下面代码中间所做的一样.
doc.paragraphs[0].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)
doc.add_paragraph('This is on the second page!')
doc.add_picture('zophie.png', width=Inches(1), height=Cm(4))
doc.save('twoPage.docx')
    def make_puzzle(self, filename='puzzle'):
        difficulty = self.diff
        option = self.option
        if difficulty == 1:
            self.difficulty = 'random.choice([self.col, self.row_rev])(word)'
        elif difficulty == 2:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev])(word)"
        elif difficulty == 3:
            self.difficulty = "random.choice([self.col, self.row_rev, self.diagup, self.diagdown])(word)"
        elif difficulty == 4:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagdown])(word)"
        elif difficulty == 5:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagup_rev, self.diagdown, self.diagdown_rev])(word)"
        elif difficulty == 6:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagup_rev, self.diagdown, self.diagdown_rev])(word)"
        self.puzzle_origin = []
        for i in range(self.height):
            self.puzzle_origin.append([])
            for j in range(self.width):
                self.puzzle_origin[i].append('0')
        print("퍼즐 만드는 중")
        words = [word[0] for word in self.word_image]
        for word in words:
            exec(self.difficulty)

        string_words = ''.join(words)
        from collections import Counter
        count_alpha = Counter(string_words)

        common_alph = ''
        for alph in count_alpha.most_common(5):
            common_alph += alph[0]

        data = ''
        if self.korean:
            f = open("random_words.txt", 'r')
            data = f.read()
            regex_f = r'[가-힣]+'
            search_target_f = data
            data = ''.join(list(set(re.findall(regex_f, search_target_f))))

        printed_words = ''
        puzzle = copy.deepcopy(self.puzzle_origin)
        for i in range(self.height):
            for j in range(self.width):
                if self.puzzle_origin[i][j] == "0":
                    fill_alph = random.choice(string.ascii_lowercase)
                    if self.korean:
                        fill_alph = random.choice(data)
                    #글자들 되도록 겹치지 않게 하기 위해서 많이 나오는 글자 한번쯤은 피할 수 있도록 한다.
                    if option == 0:
                        puzzle[i][j] = fill_alph
                    elif option == 1:
                        if fill_alph in common_alph:
                            fill_alph = random.choice(string.ascii_lowercase)
                            if self.korean:
                                fill_alph = random.choice(data)
                        puzzle[i][j] = fill_alph
                        printed_words += puzzle[i][j]
                    #글자가 겹치도록 하기 위해서 많이 나온 글자와 무작위 글자들 중에서 고르도록 한다.
                    elif option == 2:
                        common_alph_list = []
                        puzzle[i][j] = random.choice([
                            fill_alph,
                            random.choice(count_alpha.most_common(7))[0]
                        ])
                    printed_words += puzzle[i][j]

        # write to docx file
        # Write to docx to puzzle.docx
        document = Document()
        #changing the page margins
        sections = document.sections
        for section in sections:
            section.top_margin = Cm(1)
            section.bottom_margin = Cm(0.8)
            section.left_margin = Cm(2.3)
            section.right_margin = Cm(2.3)
        heading = 'Word Puzzle'
        if self.korean:
            heading = "낱말 찾기"
        head = document.add_heading(heading, 0)
        head.alignment = WD_ALIGN_PARAGRAPH.CENTER

        para_belong = document.add_paragraph('__학년 __반 이름: _______')
        para_belong.alignment = WD_ALIGN_PARAGRAPH.RIGHT

        puzzle_table = document.add_table(rows=self.height,
                                          cols=self.width,
                                          style='Table Grid')
        puzzle_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        self.set_height = 7200 / self.height
        for i, row in enumerate(puzzle_table.rows):
            #######################세로 길이 정하기!
            # accessing row xml and setting tr height
            tr = row._tr
            trPr = tr.get_or_add_trPr()
            trHeight = OxmlElement('w:trHeight')
            trHeight.set(qn('w:val'), str(self.set_height))
            trHeight.set(qn('w:hRule'), "atLeast")
            trPr.append(trHeight)

            for j, cell in enumerate(row.cells):
                #####가로 길이 정하기!
                cell.width = Inches(5)
                cell.text = puzzle[i][j]
                for paragraph in cell.paragraphs:
                    #####가운데 정렬!!
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    paragraph.style.font.bold = True
                #####상하 방향에서 가운데 정렬
                tc = cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

        if self.pic_on:
            word_num = len(words)
            if word_num <= 15:
                size = 5
            elif word_num <= 21:
                size = (word_num + 2) // 3
            else:
                size = 7
            hint_table = document.add_table(rows=(len(words) + size - 1) //
                                            size * 2,
                                            cols=size,
                                            style='Table Grid')
            hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER

            for i, row in enumerate(hint_table.rows):
                #######################세로 길이 정하기!
                if i % 2 == 0:
                    # accessing row xml and setting tr height
                    tr = row._tr
                    trPr = tr.get_or_add_trPr()
                    trHeight = OxmlElement('w:trHeight')
                    trHeight.set(qn('w:val'), '1000')
                    trHeight.set(qn('w:hRule'), "atLeast")
                    trPr.append(trHeight)
                elif i % 2 == 1:
                    # accessing row xml and setting tr height
                    tr = row._tr
                    trPr = tr.get_or_add_trPr()
                    trHeight = OxmlElement('w:trHeight')
                    trHeight.set(qn('w:val'), '60')
                    trHeight.set(qn('w:hRule'), "atLeast")
                    trPr.append(trHeight)

                for j, cell in enumerate(row.cells):
                    index = i // 2 * size + j
                    #####가로 길이 정하기!
                    cell.width = Inches(10)

                    #단어 수 만큼 반복하기
                    if index < len(words):
                        if i % 2 == 1:
                            cell.text = words[index]
                            if self.chosung:
                                word = words[index]
                                cho_word = ''
                                for chr in word:
                                    chosung = hgtk.letter.decompose(chr)[0]
                                    cho_word += chosung
                                cell.text = cho_word
                        for paragraph in cell.paragraphs:
                            if i % 2 == 0:
                                if self.word_image[index][1] == "None":
                                    cell.text = "사진 없음"
                                else:
                                    try:
                                        run = paragraph.add_run()
                                        if size > 8:
                                            run.add_picture(
                                                self.word_image[index][1],
                                                width=Mm(15),
                                                height=Mm(15))
                                        else:
                                            run.add_picture(
                                                self.word_image[index][1],
                                                width=Mm(40 - size * 3.2),
                                                height=Mm(40 - size * 3.2))
                                    except:
                                        paragraph.add_run(
                                            "에러 발생. 다른 사진 선택해주세요.")

                            #####가운데 정렬!!
                            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                            paragraph.style.font.bold = True
                    #####상하 방향에서 가운데 정렬
                    tc = cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)
        else:
            if not self.korean:
                hint_table = document.add_table(rows=1,
                                                cols=1,
                                                style='Table Grid')
                hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                hint_table_row = hint_table.rows[0]
                hint_tr = hint_table_row._tr
                hint_trPr = hint_tr.get_or_add_trPr()
                hint_trHeight = OxmlElement('w:trHeight')
                hint_trHeight.set(qn('w:val'), '1000')
                hint_trHeight.set(qn('w:hRule'), "atLeast")
                hint_trPr.append(hint_trHeight)
                hint_table_cell = hint_table_row.cells[0]
                hint = ''
                parenthesis = re.compile(r'(\s)?\(.*\)(\s)?')
                bracket = re.compile(r'(\s)?\[.*\](\s)?')
                for word in words:
                    print("사전에 찾는중... " + word)
                    req = requests.get(
                        'http://endic.naver.com/small_search.nhn?query=' +
                        word)
                    html = req.text
                    soup = BeautifulSoup(html, 'html.parser')
                    meanings = soup.select('span.fnt_k05')
                    if meanings:
                        text = meanings[0].text
                        text = re.sub(parenthesis, '', text)
                        text = re.sub(bracket, '', text)
                        print(text)
                        hint += word + "({})".format(text) + ', '
                hint_table_cell.width = Inches(100)
                for paragraph in hint_table_cell.paragraphs:
                    paragraph.add_run(hint.strip(', '))
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                tc = hint_table_cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

            else:
                if self.chosung:
                    hint_table = document.add_table(rows=1,
                                                    cols=1,
                                                    style='Table Grid')
                    hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                    hint_table_row = hint_table.rows[0]
                    hint_tr = hint_table_row._tr
                    hint_trPr = hint_tr.get_or_add_trPr()
                    hint_trHeight = OxmlElement('w:trHeight')
                    hint_trHeight.set(qn('w:val'), '1000')
                    hint_trHeight.set(qn('w:hRule'), "atLeast")
                    hint_trPr.append(hint_trHeight)
                    hint_table_cell = hint_table_row.cells[0]
                    hint = ''
                    for word in words:
                        cho_word = ''
                        for chr in word:
                            chosung = hgtk.letter.decompose(chr)[0]
                            cho_word += chosung
                        hint += cho_word + ', '
                    hint_table_cell.width = Inches(100)
                    for paragraph in hint_table_cell.paragraphs:
                        paragraph.add_run(hint.strip(', '))
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                    tc = hint_table_cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)
                else:
                    hint_table = document.add_table(rows=1,
                                                    cols=1,
                                                    style='Table Grid')
                    hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                    hint_table_row = hint_table.rows[0]
                    hint_tr = hint_table_row._tr
                    hint_trPr = hint_tr.get_or_add_trPr()
                    hint_trHeight = OxmlElement('w:trHeight')
                    hint_trHeight.set(qn('w:val'), '1000')
                    hint_trHeight.set(qn('w:hRule'), "atLeast")
                    hint_trPr.append(hint_trHeight)
                    hint_table_cell = hint_table_row.cells[0]
                    hint = ''
                    for word in words:
                        hint += word + ', '
                    hint_table_cell.width = Inches(100)
                    for paragraph in hint_table_cell.paragraphs:
                        paragraph.add_run(hint.strip(', '))
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                    tc = hint_table_cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)

        # 정답 파일 쓰기
        answ_doc = Document()
        answer_table = answ_doc.add_table(rows=self.height,
                                          cols=self.width,
                                          style='Table Grid')
        answer_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        for i, row in enumerate(answer_table.rows):
            #######################세로 길이 정하기!
            # accessing row xml and setting tr height
            tr = row._tr
            trPr = tr.get_or_add_trPr()
            trHeight = OxmlElement('w:trHeight')
            trHeight.set(qn('w:val'), str(self.set_height))
            trHeight.set(qn('w:hRule'), "atLeast")
            trPr.append(trHeight)

            for j, cell in enumerate(row.cells):
                #####가로 길이 정하기!
                cell.width = Inches(8)
                cell.text = self.puzzle_origin[i][j]
                for paragraph in cell.paragraphs:
                    #####가운데 정렬!!
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    paragraph.style.font.bold = True
                    if cell.text == '0':
                        for run in paragraph.runs:
                            run.font.color.rgb = RGBColor(255, 255, 255)
                    else:
                        for run in paragraph.runs:
                            run.font.color.rgb = RGBColor(255, 0, 0)
                #####상하 방향에서 가운데 정렬
                tc = cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

        answ_doc.save(str(self.desktop) + '\{}_정답.hwp'.format(filename))
        document.save(str(self.desktop) + '\{}.hwp'.format(filename))
        print("바탕화면에 puzzle.docx와 puzzle.hwp 로 저장")
Пример #27
0
            girl = html.xpath('string(//div[@class="other"]/a/em)')[2:3]  #确定女性
            if bool(girl) == True:
                title = html.xpath('string(//div[@class="inter"]/p)')
                a = str(title).replace('/', ',')
                imgurl = html.xpath(
                    'string(//div[@class="big_pic"]/ul/li/a/img/@src)')  # 图片地址
                if bool(imgurl) == True:  # 用布尔值确定图片地址,是否成功
                    url2 = 'http:' + imgurl
                    res = requests.get(url2, headers=headers)
                    with open('百合网/1/' + a + '.jpg', 'wb') as f:
                        f.write(res.content)

                    document.add_heading('userid: %d' % i, level=2)  # id标题
                    document.add_heading(title, level=2)  # 基本信息标题
                    document.add_picture('百合网/1/' + a + '.jpg',
                                         width=Inches(3.5),
                                         height=Inches(3.5))
                    paragraph = document.add_paragraph('_' * 30)
                    document.save('百合网.docx')
                    print('userid存在,id为: ' + str(i))
                    print(url)
                else:
                    continue

            else:
                continue

    else:
        continue
#https://profile1.baihe.com/api/getInterestPeoples?viewerId=211695885&ownerId=215848923
#https://profile1.baihe.com/api/getSimilarPeoples?viewerId=211695885&ownerId=215848923
Пример #28
0
    def report(array, year, month, day, uid):
        document = Document()  # 实例化Document
        document.styles['Normal'].font.name = u'微软雅黑'
        document.styles['Normal'].font.size = Pt(9)
        document.styles['Normal']._element.rPr.rFonts.set(
            qn('w:eastAsia'), u'微软雅黑')

        # 添加页眉
        header = document.sections[0].header
        p = header.paragraphs[0]
        p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        head = str(year) + "年" + str(month) + "月" + str(day) + "日技术分析判断报告"
        font = p.add_run(head).font
        font.size = Pt(22)
        font.bold = True

        # 绘制k线图
        df = pd.DataFrame(pd.read_excel("data/testData.xlsx"))
        df.columns = ['datetime', 'Open', 'High', 'Low', 'Close']
        time1 = pd.Timestamp(year, month, day)
        df = df.loc[df['datetime'] <= time1]
        df = df.set_index('datetime')
        mpf.plot(data=df,
                 type="candle",
                 title="",
                 ylabel="",
                 style="binance",
                 mav=(5, 10),
                 volume=False,
                 savefig="result/mplfinance.png")

        # 添加图片
        document.add_picture("result/mplfinance.png", width=Inches(4))
        # 图片居中
        last_paragraph = document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

        # 创建表格
        table = document.add_table(rows=9, cols=0, style='Table Grid')
        table.add_column(width=Cm(4.5))
        table.add_column(width=Cm(18.5))
        table.alignment = WD_ALIGN_PARAGRAPH.CENTER

        # 填充表格内容
        header = np.asarray([
            "品种名称", "趋势", "N日均线价格穿越情况", "M日、N日均线交叉和穿越情况", "RSI指标", "RSI指标背离情况",
            "MACD穿越情况", "形态提示", "前期低点、高点是否突破"
        ])
        for i in range(0, len(header)):
            table.cell(i, 0).text = header[i]

        # text
        table.cell(0, 1).text = "USDCNY"  # 品种名称
        table.cell(1, 1).text = array[0][0]  # 趋势
        # N日均线价格穿越情况
        string = ""
        for i in range(0, len(array[1])):
            if i == (len(array[1]) - 1):
                string += array[1][i]
            else:
                string += array[1][i] + "\n"
        table.cell(2, 1).text = string
        # M日、N日均线交叉和穿越情况
        string = ""
        for i in range(0, len(array[2])):
            if i == (len(array[2]) - 1):
                string += array[2][i]
            else:
                string += array[2][i] + "\n"
        table.cell(3, 1).text = string

        # RSI指标
        string = ""
        for i in range(0, len(array[3]), 2):
            if i != len(array[3]) - 1:
                string += array[3][i] + "       " + array[3][i + 1] + "\n"
            else:
                string += array[3][i]
        table.cell(4, 1).text = string
        # RSI指标背离情况
        string = ""
        for i in range(0, len(array[4])):
            if i == (len(array[4]) - 1):
                string += array[4][i]
            else:
                string += array[4][i] + "\n"
        table.cell(5, 1).text = string
        # MACD穿越情况
        string = ""
        for i in range(0, len(array[5]), 2):
            if i != len(array[5]) - 1:
                string += array[5][i] + "       " + array[5][i + 1] + "\n"
            else:
                string += array[5][i]
        table.cell(6, 1).text = string
        # 形态提示
        string = ""
        for i in range(0, len(array[6]), 3):
            if len(array[6]) - 1 - i >= 3:
                string += array[6][i] + "       " + array[6][
                    i + 1] + "       " + array[6][i + 2] + "\n"
            elif len(array[6]) - 1 - i == 2:
                string += array[6][i] + "       " + array[6][
                    i + 1] + "       " + array[6][i + 2]
            elif len(array[6]) - 1 - i == 1:
                string += array[6][i] + "       " + array[6][i + 1]
            else:
                string += array[6][i]
        table.cell(7, 1).text = string
        # 前期低点、高点是否突破
        string = array[7][0] + "            " + array[7][1]
        # print(string)
        table.cell(8, 1).text = string
        # 保存docx
        # document.save("result/report_"+time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())+".docx")
        document.save("result/report_" + uid + ".docx")
Пример #29
0
from PIL import Image
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH

img_list = ['./chair.jpg']
for i in img_list:
    im = Image.open(i)
    im.save(i, 'JPEG')

document = Document()
tables = document.tables
table = document.add_table(rows=3, cols=3)
#row_cells = table.add_row().cells

for i, image in enumerate([
        './chair.jpg', './chair.jpg', './chair.jpg', './chair.jpg',
        './chair.jpg', './chair.jpg', './chair.jpg', './chair.jpg',
        './chair.jpg'
]):
    print(i)
    row_cells = table.rows[i // 3]
    paragraph = row_cells.cells[i % 3].paragraphs[0]
    run = paragraph.add_run()
    run.add_picture(image, width=Inches(1.7))
    run = paragraph.add_run()
    run.text = "chair"
    run.bold = True
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
document.save('doc.docx')
Пример #30
0
def buildWordDoc(name, severity, host, ip, path, location, issueBackground,
                 issueDetail, remediationBackground,
                 vulnerabilityClassification):
    # refer to https://python-docx.readthedocs.io/en/latest/
    # we init the doc at the start of this script
    # then save it in the main function after everything is built.
    location = str(location)
    orig_location = location
    loc_count = location.count('/')
    status_logger.debug('Location String {} location count : {}'.format(
        location, loc_count))
    # this is a word formatting fix. If the location is / then we add host URL.
    if loc_count < 2:
        status_logger.debug('Location/Path is Default "/" ')
        # full_location = os.path.join(host, location)
        full_location = host + location
        location = full_location
    status_logger.debug('Location is Now {}'.format(location))
    # reformat data if needed
    # cheap oncoding of the comma by replacing it with |.
    # probably need to move all these to after we pass data to the word function.
    # then the commas could be fixed for building the CSV.

    issueBackground = str(issueBackground).replace('|', ',')
    remediationBackground = str(remediationBackground)
    # strip HTML tags using our function instead of string replacements inline.
    remediationBackground = strip_tags(remediationBackground)
    severity = str(severity)
    severity = severity + ' Risk'
    # use title to fix Capitals
    severity = severity.title()
    # Build Our header format here.
    build_header = '{} ({})'.format(name, severity)
    status_logger.info('Creating Issue: {}'.format(build_header))
    document.add_heading(build_header, level=2)
    document.add_heading("Vulnerable Host:", level=3)
    paragraph = document.add_paragraph(host)
    document.add_heading("Vulnerable URL:", level=3)
    # fixing location string so HTTP isnt included twice.
    if 'http' in location:
        location = orig_location
    host_url = host + location
    paragraph = document.add_paragraph(host_url)
    document.add_heading("Technical Details:", level=3)
    table = document.add_table(rows=1, cols=2)
    # adjusted cell alignment here manually.
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'IP:'
    hdr_cells[0].width = Inches(.00)
    hdr_cells[1].text = ip
    hdr_cells[1].width = Inches(.5)
    hdr_cells[1].left_margin = .1
    row_cells = table.add_row().cells
    row_cells[0].text = 'Path:'
    row_cells[0].width = Inches(.00)
    row_cells[1].text = path
    row_cells[1].width = Inches(.5)
    row_cells[1].left_margin = .1

    document.add_heading("Overview:", level=3)
    issueBackground = strip_tags(issueBackground)
    paragraph = document.add_paragraph(issueBackground)

    document.add_heading("Evidence:", level=3)
    issueDetail = strip_tags(issueDetail)
    issueDetail = issueDetail.replace('","', "")
    paragraph = document.add_paragraph(issueDetail)

    document.add_heading("Recommendation:", level=3)
    remediationBackground = strip_tags(remediationBackground)
    remediationBackground = str(remediationBackground).replace('","', ',')
    paragraph = document.add_paragraph(remediationBackground)

    document.add_heading("Additional Information:", level=3)
    # This is the fix for blank lines in CVE list
    vulnerabilityClassification = vulnerabilityClassification.split('\n')
    for i in vulnerabilityClassification:
        if len(i) > 5:
            document.add_paragraph(i, style='List Bullet')

    # add blank line to end of issue
    # paragraph = document.add_paragraph(' ')
    # paragraph = document.add_paragraph(' ')
    paragraph_format = paragraph.paragraph_format
    # formatting to keep our vulns together instead of line breaks
    paragraph_format.keep_together