Python批量查找包含多个关键词的PDF文件

在信息爆炸的时代,数据管理变得愈发重要。U盘作为一种便携式存储设备,常常承载着我们大量的个人和工作数据。然而,随着文件数量的增加,在U盘中快速找到特定文件常常成为一个令人头疼的难题。我们通常可以采用everything来快速查找我们想要的文件,但是everything只有查找功能,并没有复制功能,同时不能进行批量的查找,所以这时就可能要使用到万能的Python工具了,Python中的os标准模块可以遍历,查找文件,再用shutil来文件拷贝到指定位置。

一、查找包含单一关键词的文件

比如我们要查找U盘中包括:"翻译", "国际", "英语", "国别" 任一关键词的pdf文件,找到后复制到查找文件这一个目录下,如果找不到就重新建立查找文件这个文件夹。代码如下:

python 复制代码
import os
import shutil

# 定义要查找的关键词
keywords = ["翻译", "国际", "英语", "国别"]

# 定义要遍历的目录和目标目录
source_directory = "你的源目录路径"  # 替换为你的U盘路径,如果是当前目录下可以直接填写为"."
target_directory = os.path.join(source_directory, "查找文件")

# 如果目标目录不存在,则创建它
if not os.path.exists(target_directory):
    os.makedirs(target_directory)

# 遍历源目录下的所有文件和文件夹
for root, dirs, files in os.walk(source_directory):
    for file in files:
        # 检查文件名是否包含任何关键词,并且是PDF文件
        if any(keyword in file for keyword in keywords) and file.endswith('.pdf'):
            source_file_path = os.path.join(root, file)
            target_file_path = os.path.join(target_directory, file)
            # 复制文件到目标目录
            shutil.copy(source_file_path, target_file_path)
            print(f"已复制: {source_file_path} 到 {target_file_path}")

print("文件查找和复制完成!")

使用时,将 source_directory 替换为你要遍历的目录的路径。

运行代码,它会遍历指定的目录,查找包含关键词的PDF文件并复制到"查找文件"文件夹中。

确保在你的Python环境中安装了所需的模块(如 os 和 shutil),这些模块通常是Python标准库的一部分,无需额外安装。

二、查找多关键词同时出现的文件

查找同时包含"翻译"和"硕"两个关键词的PDF文件名,并将其复制到"查找文件"文件夹中呢?

python 复制代码
import os
import shutil

# 定义要查找的关键词
keywords = ["翻译", "硕"]

# 定义要遍历的目录和目标目录
source_directory = "你的源目录路径"  # 替换为你的源目录路径
target_directory = os.path.join(source_directory, "查找文件")

# 如果目标目录不存在,则创建它
if not os.path.exists(target_directory):
    os.makedirs(target_directory)

# 遍历源目录下的所有文件和文件夹
for root, dirs, files in os.walk(source_directory):
    for file in files:
        # 检查文件名是否同时包含所有关键词,并且是PDF文件
        if all(keyword in file for keyword in keywords) and file.endswith('.pdf'):
            source_file_path = os.path.join(root, file)
            target_file_path = os.path.join(target_directory, file)
            # 复制文件到目标目录
            shutil.copy(source_file_path, target_file_path)
            print(f"已复制: {source_file_path} 到 {target_file_path}")

print("文件查找和复制完成!")

使用说明:

将 source_directory 替换为你要遍历的目录的路径。

运行代码,它会查找同时包含"翻译"和"硕"的PDF文件并将其复制到"查找文件"文件夹中。

三、把以上两种功能合二为一

设置选项,当用户输入不同的选项就进行不同的操作。

python 复制代码
import os
import shutil

def find_files_any(source_directory, keywords):
    target_directory = os.path.join(source_directory, "查找文件_any")
    if not os.path.exists(target_directory):
        os.makedirs(target_directory)
        
    for root, dirs, files in os.walk(source_directory):
        for file in files:
            if any(keyword in file for keyword in keywords):
                print(f"找到任一关键词文件: {file}")

def find_files_all(source_directory, keywords):
    target_directory = os.path.join(source_directory, "查找文件_all")
    if not os.path.exists(target_directory):
        os.makedirs(target_directory)
        
    for root, dirs, files in os.walk(source_directory):
        for file in files:
            if all(keyword in file for keyword in keywords):
                source_file_path = os.path.join(root, file)
                target_file_path = os.path.join(target_directory, file)
                shutil.copy(source_file_path, target_file_path)
                print(f"已复制: {source_file_path} 到 {target_file_path}")

def main():
    keywords_any = ["翻译", "国际"]
    keywords_all = ["翻译", "硕"]
    
    print("请选择查找选项:")
    print("1. 查找任一关键词")
    print("2. 查找同时关键词")
    
    choice = input("请输入选项 (1 或 2): ")
    
    source_directory = input("请输入你的U盘路径: ")
    
    if choice == "1":
        find_files_any(source_directory, keywords_any)
    elif choice == "2":
        find_files_all(source_directory, keywords_all)
    else:
        print("无效选项,请重新运行程序。")

    print("文件查找完成!")

if __name__ == "__main__":
    main()

显示情况如下:

显示结果

四、采用装饰器法来写

为了使我们的代码更pythonic,我们可以设置一下装饰器,这样可以为我们设置的函数添加新的功能。

python 复制代码
import os
import shutil

def choice_decorator(func):
    def wrapper(keywords):
        print("请选择查找选项:")
        print("1. 查找任一关键词")
        print("2. 查找同时关键词")
        
        choice = input("请输入选项 (1 或 2): ")
        
        if choice not in ["1", "2"]:
            print("无效选项,请重新运行程序。")
            return
        
        source_directory = input("请输入你的U盘路径: ")
        
        if choice == "1":
            return func(source_directory, keywords[0])  # 传递任一关键词
        elif choice == "2":
            return func(source_directory, keywords[1])  # 传递同时关键词
    
    return wrapper

@choice_decorator
def find_files(source_directory, keywords):
    target_directory = os.path.join(source_directory, f"查找文件_{keywords[0]}")
    if not os.path.exists(target_directory):
        os.makedirs(target_directory)
    
    for root, dirs, files in os.walk(source_directory):
        for file in files:
            if all(keyword in file for keyword in keywords):
                source_file_path = os.path.join(root, file)
                target_file_path = os.path.join(target_directory, file)
                shutil.copy(source_file_path, target_file_path)
                print(f"已复制: {source_file_path} 到 {target_file_path}")

def main():
    keywords_any = ["翻译", "国际"]
    keywords_all = ["翻译", "硕"]
    
    # 将关键词组合放在一个列表中,以便装饰器使用
    keywords = [keywords_any, keywords_all]
    
    find_files(keywords)

    print("文件查找完成!")

if __name__ == "__main__":
    main()

五、学后总结

本来是一个遍历文件夹进行筛选的问题,现在可以采用多种方法,分不同的场景进行。最后,利用上Python的装饰器,使我们的程序变得更加高大上。同一个问题,由浅入深,用函数法、交互法、装饰器法来解决,显示出Python功能的强大和编程时的灵活性。

相关推荐
摇滚侠1 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 20
java·笔记·python
维爱智VR认知学能3 小时前
VR学能软件离线断线与乱序事件测试:确定性到达表与重放
python·单元测试·软件工程·分布式系统·离线同步
郝学胜-神的一滴3 小时前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
Thanks_ks4 小时前
SQL 注入是怎么发生的:从拼接 SQL 讲到预编译语句的防御原理
python·sqlite·orm·占位符·sql 注入·预编译语句·白名单校验
好焊孙辉4 小时前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言
布莱克6054 小时前
Swift 中的逃逸闭包与非逃逸闭包:@escaping 到底在做什么
开发语言·ios·swift·闭包·逃逸
郝学胜-神的一滴5 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
吃我一窝jio6 小时前
Java IO流核心分类与应用
java·开发语言·笔记
Kari117 小时前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
专注仿真7 小时前
仿真智能体训练:强化学习多目标奖励算法与实战
python·算法·强化学习·afsim智能体