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功能的强大和编程时的灵活性。

相关推荐
孤廖6 分钟前
吃透 C++ 栈和队列:stack/queue/priority_queue 用法 + 模拟 + STL 标准实现对比
java·开发语言·数据结构·c++·人工智能·深度学习·算法
驰羽15 分钟前
[GO]GORM中的Tag映射规则
开发语言·golang
Full Stack Developme19 分钟前
java.net 包详解
java·python·.net
非凡的世界35 分钟前
深入理解 PHP 框架里的设计模式
开发语言·设计模式·php
小龙报36 分钟前
《算法通关指南---C++编程篇(3)》
开发语言·c++·算法·visualstudio·学习方法·visual studio
凤山老林41 分钟前
排序算法:详解插入排序
java·开发语言·后端·算法·排序算法
郝学胜-神的一滴1 小时前
Effective STL 第5条:区间成员函数优先于单元素成员函数
开发语言·c++·程序人生·stl·软件工程
江太翁1 小时前
Kotlin 与 Java 互操作中常用注解
java·python·kotlin
星期天要睡觉2 小时前
深度学习——基于ResNet18迁移学习的图像分类模型
人工智能·python·分类·迁移学习
小钱c72 小时前
Python使用 pandas操作Excel文件并新增列数据
python·excel·pandas