python 写文件 换行_Python 文本中指定长度添加换行符号的小工具

工作中遇到一个问题:

对话框中显示文字,超出对话框的话就自动换行。

中文下直接判断到了一定长度换行就是了,但是换到英文下就可能出现换行时把单词分割的情况。。。

嗯。。这个问题虽然交给程序改也可以,但是自己动手更加快捷嘛。

所以索性用python编写了下面这个小工具。

说明:

这个工具会读取同一目录下的text.txt文本,自动添加换行符号然后导出到out.txt中。

添加换行符时会限制最大行数为5,在添加换行符时自动根据每行字数添加合适的字体大小标签。

实现效果:

使用前:

QfLM365.png

导出后:

JgQUpLe.png

代码贴在下方:

# 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!")

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值