使用 Python 将 OCR 文本分隔成行

Separating OCR text into lines with Python

我想做的是从一个段落创建一个列表行。线条的宽度不能超过既定的宽度量。 这里有一个 class 应该可以解决这个问题,这里是代码:

from font import Font

class Text:
        def __init__(self, text, limit, size):
                self.text = text
                self.limit = limit
                self.size = size        
                self.setText()
        def setText(self):
                textList = self.text.split(' ')
                self.newList = tempo = []
                spaceWidth = Font(self.size, ' ').width
                count = 0
                for x in textList:
                        word = Font(self.size, x)
                        count = count + word.width + spaceWidth
                        if count >= self.limit:
                                self.newList.append(' '.join(tempo))
                                tempo = []; tempo = [x]
                                count = word.width
                        else:
                                tempo.append(x)
                self.newList.append(' '.join(tempo))

如您所见,我正在使用另一个名为 Font 的 class,它是:

from PIL import Image,ImageFont

class Font:
        def __init__(self, fontSize, text):
                self.font = ImageFont.truetype('tomnr.ttf', fontSize)
                self.width, self.height = self.font.getsize(text)

代码中没有执行错误但结果不正确:例如

from text import Text

text = Text("Art inspired apparel for Creative Individuals. Do you SurVibe?", 452, 25)

print text.newList

这段代码应该做的是创建最大行数。宽度 452 像素。它应该打印

['Art inspired apparel for Creative', 'Individuals. Do you SurVibe?']

而是打印:

['Art', 'inspired', 'apparel', 'for', 'Creative', 'Art inspired apparel for Creative', 'Individuals. Do you SurVibe?']

而且我不知道发生了什么。我认为我的循环很好,一切 运行 都很顺利!我很确定这是一个愚蠢的错误,但我自己无法弄清楚。提前致谢。

错误在这里:

self.newList = tempo = []

两个变量指向同一个列表。