在 spyder 中使用 pytessaract 打印到控制台的问题

Problem with printing to console with pytessaract in spyder

我目前在 windows 10 上使用 python 3.8.5 通过 anaconda 使用 spyder,当我 运行 此代码时:

import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

img_path ='img/gotta-go-fast.jpg'

img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

result = pytesseract.image_to_string(img, lang='eng')
print(result)

spyder 中的 IPython 控制台会自动清除,但如果我只写入这样的文本文档,则不会发生同样的情况:

result = pytesseract.image_to_string(img, lang='eng')

with open('text_result.txt', mode ='w') as file:
    file.write(result)

有办法解决这个问题吗?

发现发生了什么。当 pytessaract 读取文本时,在最后一个读取行之后的新行中添加了一个 \x0c 命令。 通过删除这样的命令解决了问题:

result = pytesseract.image_to_string(img, lang='eng')
arr = result.split('\n')[0:-1]
result = '\n'.join(arr)