今天巧了,好几个同事问我要PPT,但是他们只能记得起来一些关键词,而我恰好也没有很足的印象,毕竟那是两三年前,还可能不是我做的东西!
WPS只能按照云文档进行查找关键词,那么电脑中几千个PPT要怎么找呢?(没错我电脑里真有2000个PPT (((φ(◎ロ◎;)φ))))
我们可以根据他们截取的画面关键词,来对PPT进行索引,这样可以节约一些查找文件的时间,然后采用olefile库,查找对应PPT即可。
import os
from pptx import Presentation
import olefile
def is_powerpoint_file(file_path):
"""检查文件是否为PPT或PPTX格式"""
valid_extensions = ['.ppt', '.pptx']
return any(file_path.lower().endswith(ext) for ext in valid_extensions)
def index_powerpoint_files(search_dir):
"""索引指定目录中的所有PPT和PPTX文件"""
ppt_files = []
total_files = 0
for root, _, files in os.walk(search_dir):
total_files += len(files)
for file in files:
if file.startswith("~$"): # 跳过临时文件
continue
file_path = os.path.join(root, file)
if is_powerpoint_file(file_path):
ppt_files.append(file_path)
print(f"[信息] 已索引文件总数:{total_files},PPT文件总数:{len(ppt_files)}")
return ppt_files
def search_text_in_pptx(file_path, target_text):
"""在PPTX文件中搜索目标文字"""
try:
presentation = Presentation(file_path)
for slide in presentation.slides:
for shape in slide.shapes:
if shape.has_text_frame and target_text in shape.text:
return True
except Exception as e:
print(f"[错误] 无法处理文件:{file_path},错误信息:{e}")
return False
def search_text_in_ppt(file_path, target_text):
"""在PPT文件中搜索目标文字"""
try:
if olefile.isOleFile(file_path):
with olefile.OleFileIO(file_path) as ole:
if "PowerPoint Document" in ole.listdir():
stream = ole.openstream("PowerPoint Document")
content = stream.read().decode(errors="ignore")
if target_text in content:
return True
except Exception as e:
print(f"[错误] 无法处理文件:{file_path},错误信息:{e}")
return False
def search_text_in_powerpoint_files(ppt_files, target_text):
"""在索引的PPT文件中搜索目标文字"""
result_files = []
total_files = len(ppt_files)
print(f"[信息] 开始内容搜索,共需处理 {total_files} 个文件")
for idx, file_path in enumerate(ppt_files, start=1):
print(f"[处理中] {idx}/{total_files} - 正在处理文件:{file_path}")
if file_path.lower().endswith(".pptx") and search_text_in_pptx(file_path, target_text):
result_files.append(file_path)
elif file_path.lower().endswith(".ppt") and search_text_in_ppt(file_path, target_text):
result_files.append(file_path)
return result_files
if __name__ == "__main__":
search_dir = "D:\\"
target_text = input("请输入要查找的文字(支持中文):")
print(f"[信息] 正在索引盘中的PPT文件,请稍候...\n")
ppt_files = index_powerpoint_files(search_dir)
if ppt_files:
print(f"\n[信息] 索引完成,开始搜索包含 '{target_text}' 的文件...\n")
matching_files = search_text_in_powerpoint_files(ppt_files, target_text)
if matching_files:
print("\n[结果] 找到包含目标文字的PPT文件:")
for file in matching_files:
print(file)
else:
print("\n[结果] 未找到包含该文字的PPT文件。")
else:
print("\n[信息] 未在指定目录中找到任何PPT文件。")