假设你转换程序需要一个字符串,使图像出来,我从你的问题理解的是,你的问题似乎是分裂的文本,使每个子不超过某一特定最大长度。
为此,您可以定义MAX_LENGTH
常量,然后迭代您的文本,逐字地构建子串,直到达到最大长度。
在代码:
MAX_LENGTH = 80 # characters
with open('your_text_file.txt', 'r') as fp:
text = fp.read().splitlines()
words = [ w for w in line.split(' ') for line in text ]
cur_word_index = 0
while cur_word_index < len(words):
substring = []
while cur_word_index < len(words) and len(substring) + len(words[cur_word_index]) + 1 <= MAX_LENGTH:
substring.append(" " + words[cur_word_index])
cur_word_index += 1
os.system("convert -fill black -background white -bordercolor red -border 6 -font AponaLohit.ttf -pointsize 100 label:\"%s\" \"%s.png\"" %(substring, substring))
解释算法:
我们先读所有从该文件的文本,并将其分割成单个词。请注意,我假设文本由普通空格字符分隔。 这是在做行:
with open('your_text_file.txt', 'r') as fp:
text = fp.read().splitlines()
words = [ w for w in line.split(' ') for line in text ]
然后,我们需要真正建立子。 外层while
循环的每次迭代都会创建一个新的子字符串和一个图像。 仅当子字符串的当前长度加上要添加的单词的长度,再加上一个(对于两者之间的空格字符)没有超过MAX_LENGTH
时,我们才会创建附加给它的子字符串。 这也正是内环做什么:
substring = []
while cur_word_index < len(words) and len(substring) + len(words[cur_word_index]) + 1 <= MAX_LENGTH:
substring.append(" " + words[cur_word_index])
cur_word_index += 1
需要注意的是,我们需要检查cur_word_index
没过的话名单长度。
最后,与子完成后,我们打电话给你的外部程序,并生成图像:
os.system("convert -fill black -background white -bordercolor red -border 6 -font AponaLohit.ttf -pointsize 100 label:\"%s\" \"%s.png\"" %(substring, substring))
你有语法错误? 'for i = 0:10' - 它不是Python语言。 – Dmitry