使用 pytesseract 创建变量

Creating variables with pytesseract

在我的代码中

from PIL import Image
import pytesseract

print(pytesseract.image_to_string(Image.open('test.png')))

我从 here 得到的结果(仅来自问题和答案)是:

Which team surrendered
the biggest lead in Super
Bowl history?

Atlanta Falcons

Denver Broncos

Buffalo Bills

有没有办法说第 1、2、3 行是问题,然后第 5 行是答案 1,等等?

根据您的数据在图像之间的差异,这应该有效。如果你总是有'?分裂。

image_text=pytesseract.image_to_string(Image.open('test.png'))
text_list=image_text.split('?')

这将为您提供一个包含 2 个元素的列表。首先是所有之前?和第二个。如:

print(text_list)
['Which team surrendered\nthe biggest lead in Super\nBowl history',
'\n\nAtlanta Falcons\n\nDenver Broncos\n\nBuffalo Bills']

从这里您可以定义 q 和 a。作为问答。

q =  text_list[0]
a =  [a for a in text_list[1].split('\n') if a]

上面的逻辑将保留问题的新行,并将其格式化为:

Which team surrendered
the biggest lead in Super
Bowl history?

然后变量a将填入一个答案列表,列表中没有任何空行。所以 print(a) 会 return:

['Atlanta Falcons', 'Denver Broncos', 'Buffalo Bills']

请记住,此修复取决于其中包含 ? 的文本,以定义字符串的哪一半是问题,哪一半是答案。