Python单行文本变多行程序研究
5月 1, 2021
0 Comments
""" Python单行文本变多行.py 本程序可以把单行文本变成多行, 第一个函数是原始版本,如果有英文和中文杂在一起,则每行长度不一样。 第二个版本single2multitext是改进版,每行大致一样的长度。 """ def is_chinese(uchar): """判断一个unicode是否是汉字""" if uchar >= u'\u4e00' and uchar<=u'\u9fa5': return True else: return False def single2multitext1(line, w, ofile): """ 转换单行字符串到多行,w是每行字数。 ofile是输出文件,这是第一个原始版本,留着以备忘。 """ out = open(ofile, "w") line = line.rstrip() start=0 line_length = len(line) # 字符串总长度 while line_length - start >= w: print(line[start:start+w],file=out) start += w print(line[start:],file=out) def single2multitext(line,length): """line:字符串,length:每行的字母长度,注意一个汉字占两个位""" txtbiao = [] start = 0 index = 0 # w是一个计数器,记录当前行字母数是否超出length w = 0 当前行长度 = 0 while index < len(line): if is_chinese(line[index]): # 如果是中文则占2个位 w += 2 else: w+=1 # 如果是英文则占1个位 当前行长度 += 1 if w>= length: txtbiao.append(line[start:start+当前行长度]) # 当前行长度是动态的。 start += 当前行长度 w = 0 当前行长度 = 0 index += 1 txtbiao.append(line[start:]) return txtbiao s = """测试的文本China JiangXi anyuan dist江西省萍乡市安源区有一个Python专家叫李兴球。李兴球博客www.lixingqiu.com,上面记录了很多研究成果。这就是其中之一,转载此篇文章请注意来自李兴球博客。Python创意编程专家微信公众号: 李兴球Python。回复coloradd即可获取Python创意编程教程。wechat不是QQ,wechat is not qq今天是五一劳动节。""" b = single2multitext(s,30) ##out = open('c:/t2.txt', "w") ##print(b,file=out) ##out.close() for line in b: print(line)标签:python single text convert mult text, python单行变多行, python单行文本变多行文本, python单行文本变成每行一样长度的多行