如何用Python把单行文本处理成两行并对齐?
伊谢尔伦
伊谢尔伦 2017-04-18 10:18:15
[Python讨论组]

][1]

[]内的文字新建一行秒自动对齐[]右边的文字。
如果一行内 只有一个[],一个中文占2个空格,英文占一个,就能做到,但如果出现多个[]就想不到了。

请教用python处理这样的问题应该怎么做呢?

谢谢!!

ps:[]内的字符不单一,有的是[F],有的可能是[Fm]、[Fmaj7]多个字符。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
阿神

python3

设置字体为 等宽字体

>>> s='[F]内的文字新建一行秒自动对齐[C]右边的文字'
>>> import re
>>> ptn=re.compile(r'\[([^]]+)\]([^[]+)')
>>> ss='';t=''
>>> for x,y in ptn.findall(s):
    ss+=('{:<%d}'% len(bytes(y,'gbk'))).format(x)
    t+=y

    
>>> print(ss,t,sep='\n')
F                         C         
内的文字新建一行秒自动对齐右边的文字

PHPz

另一个适应型更强的方法:

outputChords = ""
outputLyrics = ""
inBracket = False

for i in range(len(line)):

if line[i] == '[':
    inBracket = True
    outputChords = outputChords + " " * (max(0, len(outputLyrics.encode('gbk')) - len(outputChords.encode('gbk'))))
elif inBracket and line[i] == ']':
    inBracket = False
elif inBracket and line[i] == '#':
    pass
elif inBracket and str.isupper(line[i]):
    outputChords = outputChords + line[i]
elif inBracket:
    # DONT TRANSPOSE AND PUT IN OUTPUTCHORDS
    outputChords = outputChords + line[i]
else:
    outputLyrics = outputLyrics + line[i]
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号