用Python将OCR文本拆分成行

2024-06-29 00:47:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做的是从一个段落中创建一个行列表。线条的宽度不能超过确定的宽度。 这是一个应该解决这个问题的类,代码如下:

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的类,如下所示:

^{pr2}$

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

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?']

我不知道发生了什么事。我觉得我的循环很好,一切顺利!我很确定这是个愚蠢的错误,但我自己却搞不懂。提前谢谢。在


Tags: 代码textselfforsize宽度countlimit