当前位置: 首页>>代码示例>>Python>>正文


Python pptx.Presentation方法代码示例

本文整理汇总了Python中pptx.Presentation方法的典型用法代码示例。如果您正苦于以下问题:Python pptx.Presentation方法的具体用法?Python pptx.Presentation怎么用?Python pptx.Presentation使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pptx的用法示例。


在下文中一共展示了pptx.Presentation方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pptx_to_text

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def pptx_to_text(document_path, event, context):
    import pptx

    prs = pptx.Presentation(document_path)

    paragraphs = []

    for slide in prs.slides:
        for shape in slide.shapes:
            if not shape.has_text_frame: continue
            paragraphs += [' '.join([run.text for run in paragraph.runs]) for paragraph in shape.text_frame.paragraphs]
        #end for
    #end for

    return '\n\n'.join(paragraphs).strip()
#end def 
开发者ID:skylander86,项目名称:lambda-text-extractor,代码行数:18,代码来源:main.py

示例2: replace_chart_data_in_prs

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def replace_chart_data_in_prs(pres_path, slide_num, chart_name, df):
    '''
    This function 1) enters an existing powerpoint, 2) finds given slides, 3) finds given chart by name and
    4) replaces the given chart's underlying data with new data in the form of a dataframe. 

    param: pres_path - takes the full path of target file
    param: slide_num - takes a list of slides 
    param: chart_name - object name as it appears within powerpoint's Object Selection Pane
    param: df - takes a list of pandas dataframe objects 
    '''
    
    PRES_FOLDER_FOLDER = dirname(pres_path)
    PRES_NAME = basename(pres_path).replace('.pptx','')
    
    prs = Presentation(pres_path)
    
    loop_counter=0

    for i, sld in enumerate(prs.slides, start=1):
        if i in slide_num:
            for x, shp in enumerate(sld.shapes):

                if shp.name == chart_name:

                    single_df = df[loop_counter]
                    chart_data = ChartData()
                    chart_data.categories = single_df.index
 
                    for col_idx, col in enumerate(single_df.columns):
                        chart_data.add_series(col, (single_df.ix[:, col_idx].values))            
                     
                    shp.chart.replace_data(chart_data)
                    
            loop_counter+=1
                
    prs.save('{pres_path}\\{pres_name}_edited.pptx'.format(
            pres_path=PRES_FOLDER_FOLDER, 
            pres_name=PRES_NAME)) 
开发者ID:Quantipy,项目名称:quantipy,代码行数:40,代码来源:visual_editor.py

示例3: generate_presentation_using_cli_arguments

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def generate_presentation_using_cli_arguments(args) -> Tuple[Presentation, SlideDeck, str]:
    """Make a talk with the given topic."""

    runtime_checker.check_runtime_environment()

    # Print status details
    logger.info("******************************************")
    logger.info("Making {} slide talk on: {}".format(args.num_slides, args.topic))

    return generate_presentation(
        schema=args.schema,
        slides=args.num_slides,
        topic=args.topic,
        title=args.title,
        presenter=args.presenter,
        parallel=args.parallel,
        int_seed=args.int_seed,
        print_logs=args.print_logs,
        save_ppt=args.save_ppt,
        open_ppt=args.open_ppt,
    ) 
开发者ID:korymath,项目名称:talk-generator,代码行数:23,代码来源:generator.py

示例4: __init__

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def __init__(self,filename=None,chart_type_default='COLUMN_CLUSTERED',**kwargs):
        self.title=None
        self.author=None
        # self.filename = filename #导入一个存在的pptx文件
        self.chart_type_default=chart_type_default
        if filename is None:
            if os.path.exists('template.pptx'):
                prs=Presentation('template.pptx')
            elif template_pptx is not None:
                prs=Presentation(template_pptx)
            else:
                prs=Presentation()
        else :
            # 分离出路径中的文件名
            self.title=os.path.splitext(os.path.split(filename)[1])[0]
            prs=Presentation(filename)
        self.prs=prs
        title_only_slide=self._layouts()
        if title_only_slide:
            layouts=title_only_slide[0]
        else:
            layouts=[0,0]
        self.layouts_default=layouts
        for k in kwargs:
            setattr(self,k.lower(),kwargs[k]) 
开发者ID:gasongjian,项目名称:reportgen,代码行数:27,代码来源:report.py

示例5: ppt_section_slide

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def ppt_section_slide(title, subtitle, file_path):
    from pptx import Presentation
    try:
        prs = Presentation(file_path)
    except:
        prs = Presentation(r'C:\Users\adrose\Desktop\AMD PowerPoint Template.pptx')
    picture_slide_layout = prs.slide_layouts[0]
    slide = prs.slides.add_slide(picture_slide_layout)

    # for x in slide.placeholders:
    #     print('%d %s' % (x.placeholder_format.idx, x.name))

    title_placeholder = slide.placeholders[0]
    subtitle_placeholder = slide.placeholders[1]

    title_placeholder.text = title
    subtitle_placeholder.text = subtitle

    prs.save(file_path) 
开发者ID:adamerose,项目名称:pandasgui,代码行数:21,代码来源:image_viewer.py

示例6: save_figs_to_ppt

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def save_figs_to_ppt(figs, filename):
    from pptx import Presentation

    prs = Presentation()
    title_slide_layout = prs.slide_layouts[0]
    slide = prs.slides.add_slide(title_slide_layout)
    title = slide.shapes.title
    subtitle = slide.placeholders[1]

    title.text = "Hello, World!"
    subtitle.text = "python-pptx was here!"

    prs.save('test.pptx') 
开发者ID:adamerose,项目名称:pandasgui,代码行数:15,代码来源:utility.py

示例7: __init__

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def __init__(self):
        self.presentation = Presentation(os.path.join(os.path.dirname(__file__), "template.pptx"))
        self.slide_layout = self.presentation.slide_layouts[6]
        self.slide = self.presentation.slides.add_slide(self.slide_layout)
        self.shapes = self.slide.shapes 
开发者ID:yu4u,项目名称:convnet-drawer,代码行数:7,代码来源:pptx_util.py

示例8: create_new_powerpoint

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def create_new_powerpoint() -> Presentation:
    return Presentation(get_powerpoint_template_file()) 
开发者ID:korymath,项目名称:talk-generator,代码行数:4,代码来源:powerpoint_slide_creator.py

示例9: __init__

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def __init__(self, path_to_presentation, slide_layout=None, shape_properties=None):

        self.presentation  = Presentation(path_to_presentation) # TODO PptxPainter - Path checking # type: Presentation
        if slide_layout is None:
            self.default_slide_layout = None
        else:
            self.default_slide_layout = self.set_slide_layout(slide_layout)

        # Add all the dafault dicts to the class -
        if shape_properties:
            self._shape_properties = shape_properties
        else:
            self._shape_properties = PptxDefaults()

        self.textbox = self._shape_properties.textbox
        self.textbox_header = self._shape_properties.textbox_header
        self.textbox_footer = self._shape_properties.textbox_footer
        self.chart = self._shape_properties.chart
        self.table = self._shape_properties.table
        self.side_table = self._shape_properties.side_table

        charts = self._shape_properties.charts
        self.chart_bar = charts['bar']
        self.chart_bar_stacked100 = charts['bar_stacked100']
        self.chart_line = charts['line']
        self.chart_column = charts['column']
        self.chart_pie = charts['pie']

        self.slide_kwargs = {
                    'textboxs': {},
                    'charts': {},
                    'tables': {},
                    'side_tables': {},
                    } 
开发者ID:Quantipy,项目名称:quantipy,代码行数:36,代码来源:PptxPainterClass.py

示例10: rename_duplicate_shape_names

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def rename_duplicate_shape_names(pres_path, overwrite=True):
    ''' 
    Ensures all shapes have a unique name. 
    Only renames duplicates. 
    Compares shape names one slide at a time. 
    '''

    file_name = basename(pres_path).split('.')[0]
    file_path = dirname(pres_path)

    prs = Presentation(pres_path)

    for slide in prs.slides:
        shape_names = []
        for shape in slide.shapes:
            shape_names.append(shape.name)
        renamed_shapes = [x + "_" + str(i) if shape_names.count(x)>1 else x for i, x in enumerate(shape_names)]
        for s_idx, shape in enumerate(slide.shapes):
            shape.name = renamed_shapes[s_idx]

    if overwrite:
        prs.save('{pres_path}\\{pres_name}.pptx'.format(
            pres_path=file_path, 
            pres_name=file_name))
    else:
        prs.save('{pres_path}\\{pres_name}_edited.pptx'.format(
            pres_path=file_path, 
            pres_name=file_name)) 
开发者ID:Quantipy,项目名称:quantipy,代码行数:30,代码来源:visual_editor.py

示例11: get_chart_data_from_prs

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def get_chart_data_from_prs(pres_path, slide_num, chart_name):
    '''
    This function 1) pulls a given chart's data and 2) returns it as a pandas dataframe object in a list
    
    param: pres_path - full path of target file
    param: slide_num - takes a list of slides 
    param: chart_name - object name as it appears within powerpoint's Object Selection Pane
    '''
    
    prs = Presentation(pres_path)
    
    collection_of_dfs = []

    for i, sld in enumerate(prs.slides, start=1):
        if i in slide_num: 
            for x, shp in enumerate(sld.shapes):
                
                if shp.name == chart_name:
                    
                    plot = shp.chart.plots[0]

                    columns = []
                    data = []
                    for series in plot.series:
                        columns.append(str(series.name))
                        data.append(series.values)
                  
                    data = np.array(data)
                    rows = np.array(plot.categories)
                      
                    df = pd.DataFrame(data.T, index=rows, columns=columns)    
                    collection_of_dfs.append(df)

    return(collection_of_dfs) 
开发者ID:Quantipy,项目名称:quantipy,代码行数:36,代码来源:visual_editor.py

示例12: pic_to_ppt

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def pic_to_ppt(filename):  #前提是图片文件名全为数字,否则还需要修改
    if not os.path.exists(filename):
        os.mkdir(filename)
    
    ppt = pptx.Presentation()
    pic_path=[]  
    for i in os.walk(filename).__next__()[2]:
        if i.endswith('.png'):
            pic_path.append(i)
    #若是不全为数字,则可尝试运行下列代码
#    ls=[]
#    for png in pic_path:
#        s=''
#        for item in png:
#            if item<='9' and item>='0':
#                s+=item
#        ls.append(s+'.png')
#    pic_path=ls
    
    pic_path.sort(key=lambda item:int(item.split('.')[0]))
    for i in pic_path:
        i='{}/{}'.format(filename,i)
        slide = ppt.slides.add_slide(ppt.slide_layouts[1])
        slide.shapes.add_picture(i, Inches(0), Inches(0), Inches(10), Inches(7.5))
        
    fname='{}/{}.pptx'.format(filename,filename)
    ppt.save(fname)
    print('生成的文件在 {} 文件夹下的 {}.ppt 中'.format(filename,filename)) 
开发者ID:vict-cn,项目名称:crawlBaiduWenku,代码行数:30,代码来源:pic_to_ppt.py

示例13: df_to_powerpoint

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def df_to_powerpoint(filename, df, **kwargs):
    """Converts a Pandas DataFrame to a table in a new, blank PowerPoint
    presentation.

    Creates a new PowerPoint presentation with the given filename, with a single
    slide containing a single table with the Pandas DataFrame data in it.

    The table is a standard Powerpoint table, and can easily be modified with
    the Powerpoint tools, for example: resizing columns, changing formatting
    etc.

    Parameters
    ----------
    filename: Filename to save the PowerPoint presentation as

    df: pandas ``DataFrame``
        DataFrame with the data

    **kwargs
        All other arguments that can be taken by ``df_to_table()`` (such as
        ``col_formatters`` or ``rounding``) can also be passed here.

    Returns
    -------
    pptx.shapes.graphfrm.GraphicFrame
        The python-pptx table (GraphicFrame) object that was created (which can
        then be used to do further manipulation if desired)
    """
    pres = Presentation()
    blank_slide_layout = pres.slide_layouts[6]
    slide = pres.slides.add_slide(blank_slide_layout)
    table = df_to_table(slide, df, **kwargs)
    pres.save(filename)

    return table 
开发者ID:robintw,项目名称:PandasToPowerpoint,代码行数:37,代码来源:pd2ppt.py

示例14: main

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def main():
    parser = argparse.ArgumentParser(description = 'Edit pptx with text replace and csv import')
    parser.add_argument('--template',  help='template pptx file (required)', required=True)
    parser.add_argument('--model',     help='model object file with .json or .xlsx format', required=True)
    parser.add_argument('--out',       help='created pptx file (required)', required=True)
    parser.add_argument('--debug',     action='store_true', help='output verbose log')
    parser.add_argument('--skip-model-not-found', action='store_true', help='skip if specified key is not found in the model')
    opts = parser.parse_args()

    if not len(log.handlers):
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        log.addHandler(handler)

    if opts.debug:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)

    log.info(u"pptx-template version %s" % __version__)

    if opts.model.endswith(u'.xlsx'):
        slides = generate_whole_model(opts.model, {})
    else:
        if opts.model == u'-' and sys.version_info[0] == 3:
            sys.stdin = TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
        with open(opts.model, 'r', encoding='utf-8') if opts.model != u'-' else sys.stdin as m:
            models = json.load(m)
        slides = models[u'slides']

    log.info(u"Loading template pptx: %s" % opts.template)
    ppt = Presentation(opts.template)
    process_all_slides(slides, ppt, skip_model_not_found = opts.skip_model_not_found)

    log.info(u"Writing pptx: %s" % opts.out)
    ppt.save(opts.out) 
开发者ID:m3dev,项目名称:pptx-template,代码行数:38,代码来源:cli.py

示例15: build_presentation

# 需要导入模块: import pptx [as 别名]
# 或者: from pptx import Presentation [as 别名]
def build_presentation(filename):
    prs = Presentation()
    slide_layout = prs.slide_layouts[6] # blank slide
    slide = prs.slides.add_slide(slide_layout)
    prs.save(filename)
    return 
开发者ID:ym2011,项目名称:POC-EXP,代码行数:8,代码来源:CVE-2014-4114.py


注:本文中的pptx.Presentation方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。