假設你轉換程序需要一個字符串,使圖像出來,我從你的問題理解的是,你的問題似乎是分裂的文本,使每個子不超過某一特定最大長度。
爲此,您可以定義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