2017-03-07 131 views
-1

我想从一个文本文件自动拆分成较短的字符串(一个句子也许),并保存为图像文件一个非常长的字符串。我正在尝试使用ANSI字体的初步程序,但与其他ttf字体一起工作。如何将字符串转换为图像格式编程

# -*- coding: utf-8 -*- 

import os, sys 

for i=0:10 
l = i; 
for word in l: 
    os.system("convert -fill black -background white -bordercolor red -border 6 -font AponaLohit.ttf -pointsize 100 label:\"%s\" \"%s.png\""%(word, word)) 

这项计划似乎好于单一的字符串,但分裂较大的字符串转换成图像似乎很难。任何解决方案

+0

你有语法错误? 'for i = 0:10' - 它不是Python语言。 – Dmitry

回答

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没过的话名单长度。

最后,与子完成后,我们打电话给你的外部程序,并生成图像:

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