如何以编程方式将字符串转换为图像格式

时间:2017-03-07 09:42:31

标签: python

我正在尝试将文本文件中的一个非常长的字符串转换为自动拆分为较短的字符串(可能是一个句子)并保存为图像文件。我尝试的初步程序与ANSI字体挣扎,但与其他ttf字体一起工作。

 select * from Occupations where OccupationName in ('Engineer', 'Doctor', 'Lawyer')

这个程序似乎对单个字符串很有用,但是将较大的字符串拆分成图像似乎很难。任何解决方案?

1 个答案:

答案 0 :(得分:0)

假设您的转换程序接受一个字符串并将图像从中删除,我从您的问题中理解的是,您的问题似乎是将文本分开,以便每个子字符串都不会出现问题。超过一定的最大长度。

为此,您可以定义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是否不会查看“{1}}列表长度。

最后,在子字符串完成后,我们调用您的外部程序并生成图像:

 os.system("convert -fill black -background white -bordercolor red -border 6 -font AponaLohit.ttf -pointsize 100 label:\"%s\" \"%s.png\"" %(substring, substring))