使用Pytesseract遇PIL模块缺失及zsh解析错误求解决方案
解决方案
1. 解决ModuleNotFoundError: No module named 'PIL'
PIL已停止维护,官方替代库为Pillow,直接通过pip安装即可:
pip install pillow
若VSCode使用了虚拟环境,需激活对应环境后执行上述命令,或在VSCode终端切换至正确的Python解释器(右下角可切换)。
2. 解决终端执行Python代码的zsh解析错误
pytesseract.pytesseract.tesseract_cmd = r'/users/lucas/tessdata-main'是Python代码,无法直接在zsh终端执行,必须写入你的Python脚本中。同时注意两个关键点:
tesseract_cmd指向的是tesseract可执行文件的路径,而非tessdata语言包目录。比如macOS默认安装路径可能为/usr/local/bin/tesseract,手动下载的tesseract需找到其bin目录下的tesseract文件。- 若需指定语言包目录,需设置
tessdata_dir_config,而非tesseract_cmd。
修改后的代码示例:
try: from PIL import Image except ImportError: import Image import pytesseract # 设置tesseract可执行文件路径(替换为你的实际路径) pytesseract.pytesseract.tesseract_cmd = r'/usr/local/bin/tesseract' # 可选:若tesseract找不到语言包,添加以下配置 # pytesseract.pytesseract.tessdata_dir_config = r'--tessdata-dir "/users/lucas/tessdata-main"' print(pytesseract.image_to_string(Image.open('/users/lucas/desktop/image.png')))
额外验证:确保已安装tesseract本体
- macOS可通过Homebrew安装:
brew install tesseract - 终端执行
tesseract --version验证安装状态,同时可查看默认的tesseract路径。
内容的提问来源于stack exchange,提问作者Lucas Roblin
相关产品推荐
相关产品推荐

