工作中遇到一个问题:
对话框中显示文字,超出对话框的话就自动换行。
中文下直接判断到了一定长度换行就是了,但是换到英文下就可能出现换行时把单词分割的情况。。。
嗯。。这个问题虽然交给程序改也可以,但是自己动手更加快捷嘛。
所以索性用python编写了下面这个小工具。
说明:
这个工具会读取同一目录下的text.txt文本,自动添加换行符号然后导出到out.txt中。
添加换行符时会限制最大行数为5,在添加换行符时自动根据每行字数添加合适的字体大小标签。
实现效果:
使用前:
导出后:
代码贴在下方:
# coding:utf-8
import codecs
#换行符
linesign="
"
#分割长度
linelenth=21
def splitText(splitLentgh,string):
splitList=[]
index=0
while(index
str=""
if(len(string)>index+splitLentgh):
str=string[index:index+splitLentgh]
else:
str=string[index:len(string)]
if(str[-1]==" " or str[-1]=="\n" or str.find(" ")==-1):
splitList.append(str)
index=index+splitLentgh
else:
str2=string[index:index+str.rindex(" ")]
splitList.append(str2)
index=index+str.rindex(" ")
return splitList
def tryToMinSplit(splitLentgh,line):
count=1
str=""
splitList=splitText(splitLentgh,line)
while(len(splitList)>=5):
splitLentgh=splitLentgh+1
splitList=splitText(splitLentgh,line)
if(count>=5):
break
count=count+1
for i in range(len(splitList)):
if(splitList[i][0]==" "):
splitList[i]=splitList[i][1:len(splitList[i])]
if(i
str+=splitList[i]+linesign
else:
str+=splitList[i][0:-2]
return [count,str]
f2 = codecs.open('out.txt','w','utf-8')
for line in codecs.open('text.txt', encoding='utf-8'):
if(line[-1]!="\n"):
line=line+"\r\n"
tempstr=tryToMinSplit(linelenth,line)
print(tempstr)
if(tempstr[0]==1):
outstr=""+tempstr[1]+"\n"
else:
fontsize=40-int((int(tempstr[0])*1.2))
outstr=""+tempstr[1]+"\n"
f2.write(outstr)
print("done!")