?一、背景
????????在日常辦公和文檔處理中,我們常常需要在大量的Word文檔中查找特定的關(guān)鍵字,然后進(jìn)行接下來的操作,比如關(guān)鍵字替換等。手動(dòng)逐個(gè)打開并搜索文檔顯然是費(fèi)時(shí)費(fèi)力的。因此,利用Python編寫一個(gè)批量實(shí)現(xiàn)Word中查找關(guān)鍵字的程序可以大大提高效率和減少工作負(fù)擔(dān)。文章來源:http://www.zghlxwxcb.cn/news/detail-570729.html
二、開發(fā)環(huán)境
- Python編程語言:Python是一種簡潔、易讀易寫的高級(jí)編程語言,具有強(qiáng)大的數(shù)據(jù)處理和文本處理能力。本地使用Python3.6版本。
- Python-docx庫:Python-docx是一個(gè)用于操作Microsoft Word文檔(.docx文件)的第三方庫,可以讀取和修改Word文檔內(nèi)容。
- 文本編輯器或集成開發(fā)環(huán)境(IDE):選擇一個(gè)適合你的編程習(xí)慣和需求的編輯器或IDE,例如Visual Studio Code、PyCharm等。本地使用PyCharm2022。
在搭建好開發(fā)環(huán)境后,我們將使用Python編寫程序來實(shí)現(xiàn)以下步驟:文章來源地址http://www.zghlxwxcb.cn/news/detail-570729.html
- 安裝所需庫:通過命令行或Anaconda Prompt安裝Python-docx庫。
- 導(dǎo)入必要的庫:在Python代碼中引入所需的庫,例如
import docx
。 - 獲取Word文檔列表:使用Python的文件操作函數(shù)遍歷指定文件夾中的所有Word文檔,將它們的路徑存儲(chǔ)在一個(gè)列表中。
- 打開并讀取Word文檔:循環(huán)遍歷Word文檔列表,逐個(gè)打開文檔并讀取其內(nèi)容。
- 查找關(guān)鍵字:使用Python字符串操作函數(shù)在讀取的文檔內(nèi)容中查找指定的關(guān)鍵字。
- 輸出結(jié)果或執(zhí)行其他的操作:如果關(guān)鍵字在word中,則將文件移出到新建的文件夾中。
三、實(shí)現(xiàn)代碼
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:Awen
@file:task_test.py
@time:2023/07/04
@function:Python實(shí)現(xiàn)在word中批量查找關(guān)鍵字,如果關(guān)鍵字在word中,則將文件移出到新建的文件夾中
"""
import os
import shutil
from docx import Document
from docx.opc.exceptions import PackageNotFoundError
def search_keyword_in_word(keyword, file_path):
# 若報(bào)錯(cuò),則跳過,有的文件無法讀取成功
try:
document = Document(file_path)
found_paragraphs = []
for paragraph in document.paragraphs:
if keyword in paragraph.text:
found_paragraphs.append(paragraph.text)
return found_paragraphs
except PackageNotFoundError:
print(f"文件 '{file_path}' 未找到。")
pass
# 原文件夾路徑
source_file_path = 'D:\Pycharmproject2023\code_test_project\shan_test\正樣本終版\\'
# 搜索的關(guān)鍵字
keyword = '求職意向'
for filename in os.listdir(source_file_path):
try:
# 創(chuàng)建新文件夾,用于找到相應(yīng)文件之后將其移入到該文件夾中
new_directory = os.path.join(source_file_path, "data123")
os.makedirs(new_directory, exist_ok=True)
if filename.endswith('.docx'):
print(filename)
result = search_keyword_in_word(keyword, source_file_path+filename)
for paragraph in result:
print(paragraph)
# 如果求職意向中包含java字樣,則是任務(wù)目標(biāo)文件
if "java" in paragraph.lower():
new_file_path = os.path.join(new_directory, filename)
shutil.move(source_file_path+filename, new_file_path)
print(f"已移動(dòng)文件: {filename}")
# # 刪除原文件夾中的文件
# os.remove(source_file_path+filename)
# print(f"已刪除文件: {filename}")
except Exception as e:
print(f"處理文件 '{filename}' 時(shí)出現(xiàn)錯(cuò)誤: {str(e)}")
pass
到了這里,關(guān)于Python批量實(shí)現(xiàn)word中查找關(guān)鍵字的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!