完善这段代码import os import docx def search_word_docs(keyword, folder_path): for file in os.listdir(folder_path): if file.endswith(".docx"): doc = docx.Document(os.path.join(folder_path, file)) for i, paragraph in enumerate(doc.paragraphs): if keyword in paragraph.text: print(f"Found '{keyword}' in file: {file}, at paragraph: {i+1}")
时间: 2024-03-27 19:37:14 浏览: 112
以下是对代码的一些改进:
1. 错误处理:在搜索Word文档时,有可能会出现文件无法打开或者读取异常等错误。为了避免这些错误导致程序崩溃,可以添加适当的异常处理代码。
2. 使用正则表达式:在搜索文本时,可以使用正则表达式来进行更加高级的匹配操作,例如忽略大小写、只匹配整个单词等。
3. 增加参数:可以将一些参数封装成函数参数,例如是否忽略大小写、是否只匹配整个单词等,使得函数更加灵活。
改进后的代码如下所示:
``` python
import os
import docx
import re
def search_word_docs(keyword, folder_path, ignore_case=True, whole_word=False):
if ignore_case:
keyword_regex = re.compile(keyword, re.IGNORECASE)
else:
keyword_regex = re.compile(keyword)
for file in os.listdir(folder_path):
if file.endswith(".docx"):
try:
doc = docx.Document(os.path.join(folder_path, file))
for i, paragraph in enumerate(doc.paragraphs):
if whole_word:
match = re.search(r'\b{}\b'.format(keyword_regex.pattern), paragraph.text)
else:
match = keyword_regex.search(paragraph.text)
if match:
print(f"Found '{keyword}' in file: {file}, at paragraph: {i+1}")
except Exception as e:
print(f"Error occurred when processing file: {file}. Error message: {e}")
```
在改进后的代码中,增加了两个参数:ignore_case和whole_word。如果ignore_case为True,则表示搜索时忽略大小写;如果whole_word为True,则表示只匹配整个单词。同时,使用try/except语句来捕获可能出现的异常,以确保程序能够正常执行。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)