要实现档案的数字化利用,核心在于将非结构化的图片或PDF转化为可检索的文本。本指南基于Ubuntu 20.04/22.04系统,使用Python作为开发语言,Tesseract作为OCR引擎,Whoosh作为全文检索库。请确保系统已联网,严格按照以下步骤执行。
Tesseract是目前公认最优秀的开源OCR引擎。为了识别中文档案,必须安装中文语言包。同时,处理PDF文件需要poppler库。打开终端,依次执行以下命令:
安装Tesseract OCR引擎及中文语言包:
```bash sudo apt update sudo apt install tesseract-ocr tesseract-ocr-chi-sim poppler-utils ```验证安装是否成功:
```bash tesseract --version ```如果输出了版本号,说明引擎安装成功。接下来安装Python环境管理工具pip及Python依赖:
我们将使用Python来编写自动化脚本。首先安装必要的系统库,然后创建虚拟环境并安装Python依赖包。
安装Python3及pip:
```bash sudo apt install python3 python3-pip python3-venv ```创建项目目录并激活虚拟环境:
```bash mkdir archive_digital_project cd archive_digital_project python3 -m venv venv source venv/bin/activate ```安装Python核心依赖库:
这里需要安装pytesseract(Python接口)、pdf2image(PDF转图片)、Pillow(图像处理)和Whoosh(全文检索)。
在项目目录下创建一个名为ocr_engine.py的文件。这个模块将负责将输入的PDF或图片文件转换为纯文本。为了保证识别率,我们需要在代码中指定中文语言包路径,并设置合理的DPI(每英寸点数)。
创建并编辑 ocr_engine.py:
```python import pytesseract from pdf2image import convert_from_path from PIL import Image import os 设置Tesseract路径,如果是Linux系统通常不需要设置,Windows系统需指定tesseract.exe的绝对路径 pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract' class ArchiveOCR: def __init__(self, lang='chi_sim+eng'): """ 初始化OCR引擎 :param lang: 语言包,chi_sim为简体中文,eng为英文,组合使用为'chi_sim+eng' """ self.lang = lang def process_image(self, image_path): """ 处理单张图片 """ try: 打开图片 img = Image.open(image_path) 使用Tesseract识别,--psm 6 表示假设为单行文本,3为默认自动,档案页建议使用默认或6 text = pytesseract.image_to_string(img, lang=self.lang) return text except Exception as e: print(f"识别图片 {image_path} 失败: {e}") return "" def process_pdf(self, pdf_path, dpi=300): """ 处理PDF文件,将其转换为图片后再识别 :param dpi: 分辨率,越高识别越准但速度越慢,建议300 """ full_text = [] try: 将PDF转换为图片列表 pages = convert_from_path(pdf_path, dpi=dpi) print(f"正在处理PDF: {pdf_path}, 共 {len(pages)} 页") for page_num, page in enumerate(pages): 对每一页进行OCR识别 text = pytesseract.image_to_string(page, lang=self.lang) full_text.append(text) return "\n".join(full_text) except Exception as e: print(f"处理PDF {pdf_path} 失败: {e}") return "" 测试代码 if __name__ == "__main__": ocr = ArchiveOCR() 请确保当前目录下有一个test.pdf或test.jpg进行测试 print(ocr.process_pdf("test.pdf")) ```有了文本内容后,我们需要建立索引以便快速搜索。Whoosh是一个纯Python实现的全文检索库,轻量且无需安装额外服务。在项目目录下创建search_engine.py。
创建并编辑 search_engine.py:
```python from whoosh.index import create_in, exists_in, open_dir from whoosh.fields import Schema, TEXT, ID from whoosh.qparser import QueryParser import os import shutil class ArchiveSearch: def __init__(self, index_dir="indexdir"): self.index_dir = index_dir 定义索引结构:id(文件路径), title(文件名), content(识别后的文本内容) self.schema = Schema( path=ID(stored=True, unique=True), title=TEXT(stored=True), content=TEXT(stored=True) ) self.ix = self._get_index() def _get_index(self): """ 获取或创建索引对象 """ if not os.path.exists(self.index_dir): os.mkdir(self.index_dir) if exists_in(self.index_dir): ix = open_dir(self.index_dir) else: ix = create_in(self.index_dir, self.schema) return ix def add_document(self, file_path, file_name, content): """ 添加文档到索引 """ writer = self.ix.writer() 使用update_document,如果path存在则更新,不存在则新增 try: writer.update_document( path=file_path, title=file_name, content=content ) writer.commit() print(f"索引已更新: {file_name}") except Exception as e: writer.cancel() print(f"索引添加失败: {e}") def search(self, query_str, limit=10): """ 搜索关键词 """ with self.ix.searcher() as searcher: 在content和title字段中搜索 parser = QueryParser("content", self.ix.schema) query = parser.parse(query_str) results = searcher.search(query, limit=limit) print(f"找到 {len(results)} 个匹配结果:") for hit in results: print(f"文件: {hit['title']}") print(f"路径: {hit['path']}") print(f"高分片段: {hit.highlights('content')}") print("-" 20) ```
现在我们需要将OCR识别和索引创建结合起来。创建主程序main.py,它会扫描指定目录下的所有PDF和图片文件,自动完成识别和入库。
创建并编辑 main.py:
```python import os import time from ocr_engine import ArchiveOCR from search_engine import ArchiveSearch 配置项 SOURCE_DIR = "./archives" 存放档案文件的文件夹 SUPPORTED_EXTS = ['.pdf', '.jpg', '.jpeg', '.png'] def main(): 初始化引擎 ocr_engine = ArchiveOCR(lang='chi_sim+eng') search_engine = ArchiveSearch(index_dir="indexdir") 检查源目录是否存在 if not os.path.exists(SOURCE_DIR): os.makedirs(SOURCE_DIR) print(f"已创建存放目录 {SOURCE_DIR},请将档案文件放入其中后重新运行。") return files = [f for f in os.listdir(SOURCE_DIR) if os.path.splitext(f)[1].lower() in SUPPORTED_EXTS] if not files: print("未发现支持的档案文件。") return print(f"开始处理 {len(files)} 个文件...") for filename in files: file_path = os.path.join(SOURCE_DIR, filename) ext = os.path.splitext(filename)[1].lower() print(f"正在处理: {filename}") content = "" start_time = time.time() 根据文件类型调用不同的OCR方法 if ext == '.pdf': content = ocr_engine.process_pdf(file_path) else: content = ocr_engine.process_image(file_path) 将识别结果写入索引 if content.strip(): search_engine.add_document(file_path, filename, content) else: print(f"警告: {filename} 未能识别出文字内容。") end_time = time.time() print(f"处理耗时: {end_time - start_time:.2f}秒") if __name__ == "__main__": main() ```至此,所有代码已编写完毕。按照以下步骤即可完成档案的数字化利用系统搭建。
在项目根目录下创建一个名为archives的文件夹,放入几份包含中文文字的PDF文件或扫描件图片。
在终端中运行主程序,系统将自动扫描文件夹并进行OCR识别和索引构建:
```bash python main.py ```观察终端输出,你会看到每一页的识别进度和索引建立状态。首次运行会建立indexdir文件夹存储索引数据。
为了验证检索功能,我们可以直接在Python交互环境中测试。在终端输入python进入交互模式:
如果系统配置正确,屏幕上将打印出包含“合同”二字的文件名、路径以及包含该关键词的上下文高亮片段。
问题一:报错 "tesseract is not installed or it's not in your path"
解决:这是最常见的错误。请检查第一步中tesseract-ocr是否安装成功。如果在Windows下运行,必须在ocr_engine.py中取消pytesseract.pytesseract.tesseract_cmd的注释并填入正确的exe路径。
问题二:识别率极低或乱码
解决:档案扫描件的清晰度至关重要。如果是图片,请确保DPI至少为300。在process_pdf函数中,尝试将dpi参数提高到400或600。确保安装了tesseract-ocr-chi-sim简体中文语言包。
问题三:处理PDF速度慢
解决:OCR是计算密集型任务。对于大量档案,建议分批处理,或者在代码中引入Python的multiprocessing库进行多进程并行处理。在main.py中,可以将文件列表切分后分配给不同的CPU核心。