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

 更新时间:2024年11月01日 08:34:59   作者:PythonFun  
在信息爆炸的时代,数据管理变得愈发重要,本文主要为大家介绍了如何通过Python批量查找包含多个关键词的PDF文件,希望对大家有所帮助

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

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

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

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文件名,并将其复制到“查找文件”文件夹中呢?

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文件并将其复制到“查找文件”文件夹中。

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

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

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,我们可以设置一下装饰器,这样可以为我们设置的函数添加新的功能。

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

到此这篇关于Python批量查找包含多个关键词的PDF文件的文章就介绍到这了,更多相关Python查找包含多关键词的PDF内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python对列进行平移变换的方法(shift)

    python对列进行平移变换的方法(shift)

    今天小编就为大家分享一篇python对列进行平移变换的方法(shift),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • python select.select模块通信全过程解析

    python select.select模块通信全过程解析

    这篇文章主要为大家解析了python select.select模块通信全过程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-09-09
  • python 实现socket服务端并发的四种方式

    python 实现socket服务端并发的四种方式

    这篇文章主要介绍了python 实现socket服务端并发的四种方式,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2020-12-12
  • Python中的axis参数的具体使用

    Python中的axis参数的具体使用

    在我们使用Python中的Numpy和Pandas进行数据分析的时候,经常会遇到axis参数,本文就来介绍一下axis参数的具体使用,感兴趣的可以了解一下
    2021-12-12
  • Python Flask前端自动登录功能实现详解

    Python Flask前端自动登录功能实现详解

    这篇文章主要介绍了Python Flask前端自动登录功能实现,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • 用python实现一幅春联实例代码

    用python实现一幅春联实例代码

    大家好,本篇文章主要讲的是用python实现一幅春联实例代码,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • 使用Python编写一个SQL语句自动转换工具(UPDATE到INSERT转换)

    使用Python编写一个SQL语句自动转换工具(UPDATE到INSERT转换)

    在日常数据库维护和数据处理过程中,我们经常需要将UPDATE语句转换为INSERT语句,特别是在数据迁移、备份恢复或测试数据准备的场景中,本文将介绍如何使用Python编写一个自动化工具,实现UPDATE语句到INSERT语句的高效转换,需要的朋友可以参考下
    2025-09-09
  • python中的yield from语法快速学习

    python中的yield from语法快速学习

    在本篇文章里小编给大家整理的是一篇关于python中的yield from语法快速学习相关内容,有兴趣的朋友们可以参考下。
    2020-11-11
  • Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息示例

    Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息示例

    这篇文章主要介绍了Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息,涉及Python基于Selenium模块的模拟浏览器登陆、解析、抓取信息,以及MongoDB数据库的连接、写入等相关操作技巧,需要的朋友可以参考下
    2018-07-07
  • 用python画个敬业福字代码

    用python画个敬业福字代码

    大家好,本篇文章主要讲的是用python画个敬业福字代码,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01

最新评论