2017-03-07 55 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)) 
相關問題