1. 程式人生 > >Python統計多個Powerpoint檔案中幻燈片總數量

Python統計多個Powerpoint檔案中幻燈片總數量

晚上吃飯時突然想知道自己做了多少頁《Python程式設計》系列教材的配套PPT,於是就有了下面的程式碼,這套PPT綜合了《Python程式設計基礎》(ISBN:9787302410584)、《Python程式設計(第2版)》(ISBN:9787302436515)和《Python可以這樣學》(ISBN:9787302456469)以及將要出版的《Python程式設計開發寶典》4本書的內容,部分內容比書上詳細,有的地方不如書上詳細,主要是上課用,幾本書重點介紹Python 3.4.x、3.5.x、3.6.x的語法和應用,全套課件均已免費分享。

import os
import os.path
import

win32com
import win32com.client

total = 0


def pptCount(path):
    global total
    for subPath in os.listdir(path):
        subPath = os.path.join(path, subPath)
        if os.path.isdir(subPath):
            pptCount(subPath)
        elif subPath.endswith('.ppt'):
            print(subPath)
            powerpoint = win32com.client.Dispatch('PowerPoint.Application'

)
            powerpoint.Visible = 1
            ppt = powerpoint.Presentations.Open(subPath)
            win32com.client.gencache.EnsureDispatch('PowerPoint.Application')
            total += ppt.Slides.Count
            powerpoint.Quit()

pptCount('F:\\教學課件\\Python程式設計(第二版)')
print(total)

執行結果顯示:

pptx腫麼辦?

首先:

pip install python-pptx

然後:

>>> import pptx
>>> p = pptx.Presentation('f:\\1.pptx')
>>> len(p.slides)
3

昨天發文之後立刻有上海交大李老師和讀者朋友zhouyonghaha指出演算法效率太低,其實一次迴圈就可以,開始我還不太明白,想了一下果然如此,於是有了下面的高效程式碼,算作一個補充:

from random import randrange

def maxDifference2(lst):
    diff = -float('inf')    
    minCurrent = lst[0]    
    for value in lst[1:]:
        if value < minCurrent:
            minCurrent = value
        else:
            t = value-minCurrent
            if t > diff:
                diff = t
                result = (minCurrent, value)
    return result

for _ in range(10):
    print('='*20)
    lst = [randrange(1,100) for _ in range(20)]
    print(lst)
    print(maxDifference2(lst))

執行結果顯示:

====================
[22, 20, 32, 66, 22, 74, 74, 31, 88, 94, 18, 35, 47, 75, 14, 83, 44, 57, 53, 95]
(14, 95)
====================
[60, 15, 46, 36, 93, 45, 92, 56, 36, 57, 87, 80, 47, 4, 72, 18, 79, 32, 35, 1]
(15, 93)
====================
[4, 40, 92, 99, 87, 14, 52, 55, 35, 52, 1, 53, 50, 46, 39, 53, 29, 8, 45, 32]
(4, 99)
====================
[41, 53, 52, 47, 93, 67, 18, 38, 77, 12, 87, 42, 43, 2, 16, 32, 20, 54, 33, 72]
(12, 87)
====================
[68, 41, 29, 33, 23, 81, 5, 41, 17, 54, 69, 29, 90, 10, 57, 88, 14, 30, 69, 81]
(5, 90)
====================
[1, 46, 27, 47, 68, 44, 89, 15, 2, 10, 32, 90, 45, 79, 33, 99, 21, 61, 79, 21]
(1, 99)
====================
[64, 58, 97, 65, 15, 13, 35, 86, 25, 58, 26, 51, 65, 14, 6, 98, 90, 25, 98, 42]
(6, 98)
====================
[55, 14, 18, 57, 40, 27, 55, 93, 21, 16, 48, 32, 93, 69, 50, 13, 89, 98, 59, 40]
(13, 98)
====================
[11, 19, 17, 96, 21, 25, 74, 71, 78, 8, 49, 58, 57, 36, 72, 56, 83, 93, 41, 65]
(11, 96)
====================
[48, 95, 56, 44, 42, 40, 83, 86, 82, 50, 73, 88, 98, 52, 28, 60, 33, 17, 68, 59]
(40, 98)