【发布时间】: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 = "光学字符识别",我也在这个问题中添加了那个标签)