def summary_chart(data, code, filename=u'整体统计报告', summary_qlist=None, max_column_chart=20, template=None):
    if (not summary_qlist):
        try:
            summary_qlist = list(sorted(code, key=(lambda c: int(re.findall('\\d+', c)[0]))))
        except:
            summary_qlist = list(code.keys())
    sample_len = len(data)
    prs = (rpt.Report(template) if template else rpt.Report())
    if (not os.path.exists('.\\out')):
        os.mkdir('.\\out')
    Writer = pd.ExcelWriter((('.\\out\\' + filename) + '.xlsx'))
    result = {}
    conclusion = pd.DataFrame(index=summary_qlist, columns=[u'内容', u'题型', u'样本数'])
    conclusion.to_excel(Writer, u'索引')
    prs.add_cover(title=filename)
    title = u'说明'
    qtype_count = [code[k]['qtype'] for k in code]
    qtype_count = [[qtype, qtype_count.count(qtype)] for qtype in set(qtype_count)]
    qtype_count = sorted(qtype_count, key=(lambda x: x[1]), reverse=True)
    summary = '该数据一共有{}个题目,其中有'.format(len(code))
    summary += ','.join(['{} {} 道'.format(t[0], t[1]) for t in qtype_count])
    summary += '.\n 经统计, 该数据有效样本数为 {} 份。下表是在该样本数下，各比例对应的置信区间(置信水平95%).'.format(sample_len)
    w = pd.DataFrame(index=[((i + 1) * 0.05) for i in range(10)], columns=['比例', '置信区间'])
    w['比例'] = w.index
    w['置信区间'] = w['比例'].map((lambda x: confidence_interval(x, sample_len)))
    w['置信区间'] = w['置信区间'].map((lambda x: '±{:.1f}%'.format((x * 100))))
    w['比例'] = w['比例'].map((lambda x: '{:.0f}% / {:.0f}%'.format((x * 100), (100 - (100 * x)))))
    w = w.set_index('比例')
    prs.add_slide(data={'data': w, 'slide_type': 'table'}, title=title, summary=summary)
    for qq in summary_qlist:
        '\n        特殊题型处理\n        整体满意度题：后期归为数值类题型\n        '
        qtitle = code[qq]['content']
        qlist = code[qq]['qlist']
        qtype = code[qq]['qtype']
        if (not (set(qlist) <= set(data.columns))):
            continue
        sample_len_qq = data[code[qq]['qlist']].notnull().T.any().sum()
        conclusion.loc[(qq, u'内容')] = qtitle
        conclusion.loc[(qq, u'题型')] = qtype
        conclusion.loc[(qq, u'样本数')] = sample_len_qq
        if (qtype == '填空题'):
            startcols = 0
            for qqlist in qlist:
                tmp = pd.DataFrame(data[qqlist].value_counts()).reset_index()
                tmp.to_excel(Writer, qq, startcol=startcols, index=False)
                startcols += 3
            continue
        if (qtype not in [u'单选题', u'多选题', u'排序题', u'矩阵单选题']):
            continue
        try:
            result_t = table(data[qlist], code=code[qq])
        except:
            print(u'脚本处理 {} 时出了一点小问题.....'.format(qq))
            continue
        t = result_t['fop']
        t1 = result_t['fo']
        if ('code_order' in code[qq]):
            code_order = code[qq]['code_order']
            code_order = [q for q in code_order if (q in t.index)]
            if (u'合计' in t.index):
                code_order = (code_order + [u'合计'])
            t = pd.DataFrame(t, index=code_order)
            t1 = pd.DataFrame(t1, index=code_order)
        t.fillna(0, inplace=True)
        t1.fillna(0, inplace=True)
        Writer_rows = 0
        t2 = pd.concat([t, t1], axis=1)
        t2.to_excel(Writer, qq, startrow=Writer_rows, index_label=qq, float_format='%.3f')
        Writer_rows += (len(t2) + 2)
        summary = ''
        if (qtype in ['单选题', '多选题']):
            try:
                gof_result = gof_test(t1)
            except:
                gof_result = (- 2)
            if (gof_result == 1):
                summary += '拟合优度检验*显著*'
            elif (gof_result == 0):
                summary += '拟合优度检验*不显著*'
            else:
                summary += '不满足拟合优度检验条件'
        if (qtype == '多选题'):
            tmp = data[qlist].rename(columns=code[qq]['code'])
            tmp_t = ((len(tmp) * tmp.shape[1]) * np.log(tmp.shape[1]))
            if (tmp_t < 20000):
                minSup = 0.08
                minConf = 0.4
            elif (tmp_t < 50000):
                minSup = 0.15
                minConf = 0.6
            else:
                minSup = 0.2
                minConf = 0.6
            (aso_result, rules, freq) = association_rules(tmp, minSup=minSup, minConf=minConf)
            numItem_mean = (t1.sum().sum() / sample_len_qq)
            if (u'合计' in t1.index):
                numItem_mean = (numItem_mean / 2)
            if aso_result:
                summary += ' || 平均每个样本选了{:.1f}个选项 || 找到的关联规则如下(只显示TOP4)：\n{}'.format(numItem_mean, aso_result)
                rules.to_excel(Writer, qq, startrow=Writer_rows, index=False, float_format='%.3f')
                Writer_rows += (len(rules) + 2)
            else:
                summary += ' || 平均每个样本选了{:.1f}个选项 || 没有找到关联性较大的规则'.format(numItem_mean)
        if ((qtype in [u'单选题']) and ('fw' in result_t)):
            tmp = u'加权平均值'
            if (('name' in code[qq]) and (code[qq]['name'] == u'满意度')):
                tmp = u'满意度平均值'
            elif (('name' in code[qq]) and (code[qq]['name'] == 'NPS')):
                tmp = u'NPS值'
            summary += ' || {}为：{:.3f}'.format(tmp, result_t['fw'])
        elif (qtype == '排序题'):
            summary += ' 此处“综合”指标的计算方法为 :={}/总频数.'.format(result_t['weight'])
        if (len(summary) == 0):
            summary += u'这里是结论区域'
        if (qtype in [u'单选题', u'多选题', u'排序题']):
            plt_data = (t * 100)
        else:
            plt_data = t.copy()
        if (u'合计' in plt_data.index):
            plt_data.drop([u'合计'], axis=0, inplace=True)
        result[qq] = plt_data
        title = ((((qq + '[') + qtype) + ']: ') + qtitle)
        footnote = (u'数据来源于%s,样本N=%d' % (qq, sample_len_qq))
        if (len(t) > max_column_chart):
            prs.add_slide(data={'data': plt_data[::(- 1)], 'slide_type': 'chart', 'type': 'BAR_CLUSTERED'}, title=title, summary=summary, footnote=footnote)
        elif ((len(t) > 3) or ((len(plt_data.shape) > 1) and (plt_data.shape[1] > 1))):
            prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'COLUMN_CLUSTERED'}, title=title, summary=summary, footnote=footnote)
        else:
            prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'PIE'}, title=title, summary=summary, footnote=footnote)
        if ((qtype == u'矩阵单选题') and ('fw' in result_t)):
            plt_data = result_t['fw']
            plt_data.rename(columns={u'加权': u'平均值'}, inplace=True)
            plt_data.to_excel(Writer, qq, startrow=Writer_rows, float_format='%.3f')
            Writer_rows = (len(plt_data) + 2)
            plt_data.fillna(0, inplace=True)
            title = ('[平均值]' + title)
            summary = ((summary + ' || 该平均分采用的权值是:\n') + result_t['weight'])
            if (len(plt_data) > max_column_chart):
                prs.add_slide(data={'data': plt_data[::(- 1)], 'slide_type': 'chart', 'type': 'BAR_STACKED'}, title=title, summary=summary, footnote=footnote)
            else:
                prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'COLUMN_STACKED'}, title=title, summary=summary, footnote=footnote)
        if ((qtype == u'排序题') and ('TOPN' in result_t)):
            plt_data = result_t['TOPN']
            tmp = pd.concat([result_t['TOPN'], result_t['TOPN_fo']], axis=1)
            tmp.to_excel(Writer, qq, startrow=Writer_rows, float_format='%.3f')
            Writer_rows = (len(plt_data) + 2)
            plt_data = (plt_data * 100)
            if ('code_order' in code[qq]):
                code_order = code[qq]['code_order']
                if (u'合计' in plt_data.index):
                    code_order = (code_order + [u'合计'])
                plt_data = pd.DataFrame(plt_data, index=code_order)
            plt_data.fillna(0, inplace=True)
            title = ('[TOPN]' + title)
            if (len(plt_data) > max_column_chart):
                prs.add_slide(data={'data': plt_data[::(- 1)], 'slide_type': 'chart', 'type': 'BAR_STACKED'}, title=title, summary=summary, footnote=footnote)
            else:
                prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'COLUMN_STACKED'}, title=title, summary=summary, footnote=footnote)
    try:
        prs.save((('.\\out\\' + filename) + u'.pptx'))
    except:
        prs.save((('.\\out\\' + filename) + u'_副本.pptx'))
    conclusion.to_excel(Writer, '索引')
    Writer.save()
    return result
def summary_chart(data, code, filename=u'整体统计报告', summary_qlist=None, max_column_chart=20, template=None):
    if (not summary_qlist):
        try:
            summary_qlist = list(sorted(code, key=(lambda c: int(re.findall('\\d+', c)[0]))))
        except:
            summary_qlist = list(code.keys())
    sample_len = len(data)
    prs = (rpt.Report(template) if template else rpt.Report())
    if (not os.path.exists('.\\out')):
        os.mkdir('.\\out')
    Writer = pd.ExcelWriter((('.\\out\\' + filename) + '.xlsx'))
    result = {}
    conclusion = pd.DataFrame(index=summary_qlist, columns=[u'内容', u'题型', u'样本数'])
    conclusion.to_excel(Writer, u'索引')
    prs.add_cover(title=filename)
    title = u'说明'
    qtype_count = [code[k]['qtype'] for k in code]
    qtype_count = [[qtype, qtype_count.count(qtype)] for qtype in set(qtype_count)]
    qtype_count = sorted(qtype_count, key=(lambda x: x[1]), reverse=True)
    summary = '该数据一共有{}个题目,其中有'.format(len(code))
    summary += ','.join(['{} {} 道'.format(t[0], t[1]) for t in qtype_count])
    summary += '.\n 经统计, 该数据有效样本数为 {} 份。下表是在该样本数下，各比例对应的置信区间(置信水平95%).'.format(sample_len)
    w = pd.DataFrame(index=[((i + 1) * 0.05) for i in range(10)], columns=['比例', '置信区间'])
    w['比例'] = w.index
    w['置信区间'] = w['比例'].map((lambda x: confidence_interval(x, sample_len)))
    w['置信区间'] = w['置信区间'].map((lambda x: '±{:.1f}%'.format((x * 100))))
    w['比例'] = w['比例'].map((lambda x: '{:.0f}% / {:.0f}%'.format((x * 100), (100 - (100 * x)))))
    w = w.set_index('比例')
    prs.add_slide(data={'data': w, 'slide_type': 'table'}, title=title, summary=summary)
    for qq in summary_qlist:
        '\n        特殊题型处理\n        整体满意度题：后期归为数值类题型\n        '
        qtitle = code[qq]['content']
        qlist = code[qq]['qlist']
        qtype = code[qq]['qtype']
        if (not (set(qlist) <= set(data.columns))):
            continue
        sample_len_qq = data[code[qq]['qlist']].notnull().T.any().sum()
        conclusion.loc[(qq, u'内容')] = qtitle
        conclusion.loc[(qq, u'题型')] = qtype
        conclusion.loc[(qq, u'样本数')] = sample_len_qq
        if (qtype == '填空题'):
            startcols = 0
            for qqlist in qlist:
                tmp = pd.DataFrame(data[qqlist].value_counts()).reset_index()
                tmp.to_excel(Writer, qq, startcol=startcols, index=False)
                startcols += 3
            continue
        if (qtype not in [u'单选题', u'多选题', u'排序题', u'矩阵单选题']):
            continue
        try:
            result_t = table(data[qlist], code=code[qq])
        except:
            print(u'脚本处理 {} 时出了一点小问题.....'.format(qq))
            continue
        t = result_t['fop']
        t1 = result_t['fo']
        if ('code_order' in code[qq]):
            code_order = code[qq]['code_order']
            code_order = [q for q in code_order if (q in t.index)]
            if (u'合计' in t.index):
                code_order = (code_order + [u'合计'])
            t = pd.DataFrame(t, index=code_order)
            t1 = pd.DataFrame(t1, index=code_order)
        t.fillna(0, inplace=True)
        t1.fillna(0, inplace=True)
        Writer_rows = 0
        t2 = pd.concat([t, t1], axis=1)
        t2.to_excel(Writer, qq, startrow=Writer_rows, index_label=qq, float_format='%.3f')
        Writer_rows += (len(t2) + 2)
        summary = 
        if (qtype in ['单选题', '多选题']):
            try:
                gof_result = gof_test(t1)
            except:
                gof_result = (- 2)
            if (gof_result == 1):
                summary += '拟合优度检验*显著*'
            elif (gof_result == 0):
                summary += '拟合优度检验*不显著*'
            else:
                summary += '不满足拟合优度检验条件'
        if (qtype == '多选题'):
            tmp = data[qlist].rename(columns=code[qq]['code'])
            tmp_t = ((len(tmp) * tmp.shape[1]) * np.log(tmp.shape[1]))
            if (tmp_t < 20000):
                minSup = 0.08
                minConf = 0.4
            elif (tmp_t < 50000):
                minSup = 0.15
                minConf = 0.6
            else:
                minSup = 0.2
                minConf = 0.6
            (aso_result, rules, freq) = association_rules(tmp, minSup=minSup, minConf=minConf)
            numItem_mean = (t1.sum().sum() / sample_len_qq)
            if (u'合计' in t1.index):
                numItem_mean = (numItem_mean / 2)
            if aso_result:
                summary += ' || 平均每个样本选了{:.1f}个选项 || 找到的关联规则如下(只显示TOP4)：\n{}'.format(numItem_mean, aso_result)
                rules.to_excel(Writer, qq, startrow=Writer_rows, index=False, float_format='%.3f')
                Writer_rows += (len(rules) + 2)
            else:
                summary += ' || 平均每个样本选了{:.1f}个选项 || 没有找到关联性较大的规则'.format(numItem_mean)
        if ((qtype in [u'单选题']) and ('fw' in result_t)):
            tmp = u'加权平均值'
            if (('name' in code[qq]) and (code[qq]['name'] == u'满意度')):
                tmp = u'满意度平均值'
            elif (('name' in code[qq]) and (code[qq]['name'] == 'NPS')):
                tmp = u'NPS值'
            summary += ' || {}为：{:.3f}'.format(tmp, result_t['fw'])
        elif (qtype == '排序题'):
            summary += ' 此处“综合”指标的计算方法为 :={}/总频数.'.format(result_t['weight'])
        if (len(summary) == 0):
            summary += u'这里是结论区域'
        if (qtype in [u'单选题', u'多选题', u'排序题']):
            plt_data = (t * 100)
        else:
            plt_data = t.copy()
        if (u'合计' in plt_data.index):
            plt_data.drop([u'合计'], axis=0, inplace=True)
        result[qq] = plt_data
        title = ((((qq + '[') + qtype) + ']: ') + qtitle)
        footnote = (u'数据来源于%s,样本N=%d' % (qq, sample_len_qq))
        if (len(t) > max_column_chart):
            prs.add_slide(data={'data': plt_data[::(- 1)], 'slide_type': 'chart', 'type': 'BAR_CLUSTERED'}, title=title, summary=summary, footnote=footnote)
        elif ((len(t) > 3) or ((len(plt_data.shape) > 1) and (plt_data.shape[1] > 1))):
            prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'COLUMN_CLUSTERED'}, title=title, summary=summary, footnote=footnote)
        else:
            prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'PIE'}, title=title, summary=summary, footnote=footnote)
        if ((qtype == u'矩阵单选题') and ('fw' in result_t)):
            plt_data = result_t['fw']
            plt_data.rename(columns={u'加权': u'平均值'}, inplace=True)
            plt_data.to_excel(Writer, qq, startrow=Writer_rows, float_format='%.3f')
            Writer_rows = (len(plt_data) + 2)
            plt_data.fillna(0, inplace=True)
            title = ('[平均值]' + title)
            summary = ((summary + ' || 该平均分采用的权值是:\n') + result_t['weight'])
            if (len(plt_data) > max_column_chart):
                prs.add_slide(data={'data': plt_data[::(- 1)], 'slide_type': 'chart', 'type': 'BAR_STACKED'}, title=title, summary=summary, footnote=footnote)
            else:
                prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'COLUMN_STACKED'}, title=title, summary=summary, footnote=footnote)
        if ((qtype == u'排序题') and ('TOPN' in result_t)):
            plt_data = result_t['TOPN']
            tmp = pd.concat([result_t['TOPN'], result_t['TOPN_fo']], axis=1)
            tmp.to_excel(Writer, qq, startrow=Writer_rows, float_format='%.3f')
            Writer_rows = (len(plt_data) + 2)
            plt_data = (plt_data * 100)
            if ('code_order' in code[qq]):
                code_order = code[qq]['code_order']
                if (u'合计' in plt_data.index):
                    code_order = (code_order + [u'合计'])
                plt_data = pd.DataFrame(plt_data, index=code_order)
            plt_data.fillna(0, inplace=True)
            title = ('[TOPN]' + title)
            if (len(plt_data) > max_column_chart):
                prs.add_slide(data={'data': plt_data[::(- 1)], 'slide_type': 'chart', 'type': 'BAR_STACKED'}, title=title, summary=summary, footnote=footnote)
            else:
                prs.add_slide(data={'data': plt_data, 'slide_type': 'chart', 'type': 'COLUMN_STACKED'}, title=title, summary=summary, footnote=footnote)
    try:
        prs.save((('.\\out\\' + filename) + u'.pptx'))
    except:
        prs.save((('.\\out\\' + filename) + u'_副本.pptx'))
    conclusion.to_excel(Writer, '索引')
    Writer.save()
    return result