本地文件的搜索与读取指南
立即解锁
发布时间: 2025-09-03 01:43:59 阅读量: 2 订阅数: 13 AIGC 

# 本地文件的搜索与读取指南
## 1. 读取 PDF 文件
### 1.1 准备工作
PDF(Portable Document Format)是一种常见的文档格式,它最初是为任何打印机描述文档而设计的,能确保文档打印效果与显示一致,常用于共享最终的只读文档。
要读取 PDF 文件,我们将使用 PyPDF2 模块,需将其添加到虚拟环境中:
```bash
$ echo "PyPDF2==1.26.0" >> requirements.txt
$ pip install -r requirements.txt
```
在 GitHub 目录 Chapter03/documents 中有两个测试文档 `document-1.pdf` 和 `document-2.pdf`,它们大多包含 Lorem Ipsum 文本(占位文本),`document-2.pdf` 需要密码 `automate` 才能打开。
### 1.2 操作步骤
1. **导入模块**:
```python
>>> from PyPDF2 import PdfFileReader
```
2. **打开文件并创建 PDF 文档对象**:
```python
>>> file = open('document-1.pdf', 'rb')
>>> document = PdfFileReader(file)
```
3. **获取页面数量并检查是否加密**:
```python
>>> document.numPages
3
>>> document.isEncrypted
False
```
4. **获取文档创建日期和生成器信息**:
```python
>>> document.documentInfo['/CreationDate']
"D:20180624111518Z00'00'"
>>> document.documentInfo['/Producer']
'Mac OS X 10.13.5 Quartz PDFContext'
```
5. **获取第一页文本**:
```python
>>> document.pages[0].extractText()
'!A VERY IMPORTANT DOCUMENT \nBy James McCormac CEO Loose Seal Inc '
```
6. **获取第二页文本**:
```python
>>> document.pages[1].extractText()
'"!This is an example of a test document that is stored in PDF format. It contains some \nsentences to describe what it is and the it has lore ipsum text.\n!"\nLorem ipsum dolor sit amet, consectetur adipiscing elit. ...$'
```
7. **关闭当前文件并打开加密文件**:
```python
>>> file.close()
>>> file = open('document-2.pdf', 'rb')
>>> document = PdfFileReader(file)
```
8. **检查文件是否加密**:
```python
>>> document.isEncrypted
True
>>> document.numPages
...
PyPDF2.utils.PdfReadError: File has not been decrypted
```
9. **解密文件并访问内容**:
```python
>>> document.decrypt('automate')
1
>>> document.numPages
3
>>> document.pages[0].extractText()
'!A VERY IMPORTANT DOCUMENT \nBy James McCormac CEO Loose Seal Inc '
```
10. **关闭文件**:
```python
>>> file.close()
```
### 1.3 工作原理
打开文档后,文档对象可用于访问文档。有用的属性包括 `.numPages`(页面数量)和 `.pages`(页面列表),`.documentInfo` 存储文档的元数据。每个页面对象可通过 `.extractText()` 方法提取文本,但该方法有一定局限性,对于结构良好的文本效果较好。
对于加密文件,可通过 `.isEncrypted` 检测是否加密,使用 `.decrypt` 方法并提供正确密码进行解密。
### 1.4 更多注意事项
PDF 格式灵活但解析处理较难,部分 PDF 可能包含文本图像(如扫描文档),此时需使用 OCR 等方法提取文本。PyPDF2 处理图像能力有限,可将 PDF 转换为图像集合,使用 Pillow 等工具处理。
某些加密方法 PyPDF2 可能不支持,会抛出 `NotImplementedError`,可使用 QPDF 进行解密:
```bash
$ qpdf --decrypt --password=PASSWORD encrypted.pdf output-decrypted.pdf
```
## 2. 读取 Word 文档
### 2.1 准备工作
Word 文档(.docx)主要存储文本,通常由 Microsoft Office 生成,也有其他工具可生成兼容文件,常用于共享可编辑文档。
要读取 Word 文档,我们使用 python-docx 模块,将其添加到虚拟环境:
```bash
$ echo "python-docx==0.8.10" >> requirements.txt
$ pip install -r requirements.txt
```
在 GitHub Chapter04/documents 目录有测试文件 `document-1.docx`,遵
0
0
复制全文
相关推荐










