【问题标题】:Separating OCR text into lines with Python用 Python 将 OCR 文本分成几行
【发布时间】:2015-01-18 22:51:01
【问题描述】:

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

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 的类,这里是:

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

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

【问题讨论】:

  • (当你说文本时,你的意思不是人们理解的“字符串”,而是“OCR 文本”。)
  • 光学字符识别?我在谷歌上搜索了这个词,结果就是@smci
  • (是的,OCR = "光学字符识别",我也在这个问题中添加了那个标签)

标签: python ocr


【解决方案1】:

错误在这里:

self.newList = tempo = []

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

【讨论】:

  • 我很惭愧。那是错误。我还不能“在 5 分钟内”将此标记为正确答案。但是非常感谢。我在这里疯了。愚蠢的错误。
  • 这是比较烦人的 Python 疣之一。类似于将函数 args 初始化为空列表 def func(..., some_list_arg = [])
  • @smci 对我来说这是一个不错的功能。你可以做result = cache[key] = foo()
  • 它可以是好是坏,取决于别名,以及 foo() 是返回列表/元组还是原始类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多