鱼C论坛

 找回密码
 立即注册
查看: 4317|回复: 17

[技术交流] 鱼C论坛Python精英挑战赛(第二季01期)

[复制链接]
发表于 2017-8-7 21:05:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 jerryxjr1220 于 2017-8-10 21:18 编辑

鱼C论坛Python精英挑战赛第二季又开始啦!

本季挑战赛依旧会有精彩的题目供大家挑战,大量鱼币奖励等你赢取!

11.jpg

比赛规则:程序结果正确,运行效率高,秉承python简洁优雅的理念。

比赛截止日期:8月10日24时

优胜者会优先从普通鱼油中产生,给予100鱼币奖励.

本期题目:字符串格式化输出“两端对齐”

本期题目很简单,给定一组字符串,字符串均由标准英语单词、空格及常用英语标点符号组成,要求编写函数,根据给定宽度,按照“两端对齐”的格式化输出。

“两端对齐”格式要求:
1. 每行必须以字母或标点符号开头,但表示结束的标点符号,如逗号、句号、问好、感叹号等不允许出现在每行开头。每行必须以字母或标点符号结尾,空格不允许出现在每行的开头和结尾。
2. 若某一行只容得下一个单词,则该行按照左对齐格式输出,行尾同样不需要用空格填充。
3. 参数width肯定会大于字符串中最长单词的长度,不需要考虑单词长度超过width的情况。
4. 用空格填充时,应当遵循“空格尽可能均匀分布到单词与单词之间”的原则。
5. 若有不明白处,可以调用word,设置“两端对齐”的格式进行测试。

例如,给定字符串txt,自定义函数adjust_txt(txt, width),输出output。
  1. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

  2. def adjust_txt(txt, width):
  3.     "Your code here."
  4.     return output

  5. output = adjust_txt(txt, 30)
  6. print(output)
复制代码

格式化输出:
  1. Hot work is one of the typical
  2. high  risk  work in work shop,
  3. if  out  of  control,  it will
  4. cause  tragedy.  We manage our
  5. hot  work basing on the FM hot
  6. work  permit  system. Then, to
  7. make  sure  the  fire risk are
  8. eliminated before we start hot
  9. work,   what   should  we  do?
  10. Please  refer  to  this week's
  11. topic,    hot   work   permit.
复制代码


第一期的题目难度不大,希望大家多多参与!
@小甲鱼 @SixPy @~风介~ @冬雪雪冬

感谢@小甲鱼 老师鼎力支持,本届优胜者鱼币奖励由小甲鱼老师倾情赞助!

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +5 收起 理由
~风介~ + 5 + 5 + 5 支持楼主!

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-8-7 22:21:30 | 显示全部楼层
边想边写边改,弄得很乱,先凑合着看吧,以后再修改优化。
  1. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."
  2. def adjust_txt(txt, width):
  3.     txtlist = txt.split()
  4.     newtxt = ''
  5.     while True:
  6.         lenght = 0
  7.         newlist = []
  8.         for i in range(len(txtlist)):
  9.             lenght += len(txtlist[i]) + 1
  10.             if lenght > width + 1:
  11.                 lenght -= len(txtlist[i]) + 1
  12.                 i -= 1
  13.                 break
  14.             newlist.append(txtlist[i])
  15.         if len(txtlist) == 0:
  16.             break
  17.         txtlist = txtlist[i + 1:]
  18.         sum1 = sum([len(word) for word in newlist])
  19.         if len(newlist) > 1:
  20.             d, m = divmod(width - sum1, len(newlist) - 1)
  21.             for i in range(len(newlist)):
  22.                 if m > 0:
  23.                     newlist[i] += ' '* (d + 1)
  24.                     m -= 1
  25.                 else:
  26.                     newlist[i] += ' '* d
  27.             newtxt += ''.join(newlist) +' \n'
  28.         else:
  29.             newtxt += newlist[0] + '\n'
  30.     newtxt.rstrip('\n')
  31.     return(newtxt)
复制代码


30
  1. Hot work is one of the typical  
  2. high  risk  work in work shop,  
  3. if  out  of  control,  it will  
  4. cause  tragedy.  We manage our  
  5. hot  work basing on the FM hot  
  6. work  permit  system. Then, to  
  7. make  sure  the  fire risk are  
  8. eliminated before we start hot  
  9. work,   what   should  we  do?   
  10. Please  refer  to  this week's  
  11. topic,    hot   work   permit.
复制代码


20
  1. Hot  work  is one of  
  2. the   typical   high   
  3. risk  work  in  work   
  4. shop,   if   out  of   
  5. control,   it   will   
  6. cause   tragedy.  We   
  7. manage  our hot work  
  8. basing on the FM hot  
  9. work  permit system.  
  10. Then,  to  make sure  
  11. the  fire  risk  are   
  12. eliminated before we  
  13. start hot work, what  
  14. should we do? Please  
  15. refer to this week's  
  16. topic,    hot   work   
  17. permit.
复制代码


60
  1. Hot  work is one of the typical high risk work in work shop,  
  2. if  out of control, it will cause tragedy. We manage our hot  
  3. work  basing on the FM hot work permit system. Then, to make  
  4. sure  the fire risk are eliminated before we start hot work,  
  5. what  should  we  do? Please refer to this week's topic, hot  
  6. work                                                 permit.
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-8 10:36:13 | 显示全部楼层
作为小菜鸟我之后先看看了有些函数还没有学到。支持鱼神!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-8 17:42:46 | 显示全部楼层
本帖最后由 qitan888 于 2017-8-10 20:53 编辑

哦,未考虑到1行只有1个单词的。简单的加了个判断语句。。。。

  1. #!/bin/python
  2. #coding=utf-8
  3. import textwrap,sys

  4. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

  5. def adjust_txt(txt, width):
  6.     t1 = textwrap.fill(txt,width)
  7.     t2 = t1.split('\n')
  8.     output = ''
  9.     for t3 in t2:
  10.         wordlist = t3.split(' ')
  11.         space = width-len(t3)
  12.         place = len(wordlist) - 1
  13.         s3 = ''
  14.         if place == 0:
  15.             s3 = t3
  16.         else:
  17.             if space > 0:
  18.                 if space%place != 0:
  19.                     for i in range(space%place):
  20.                         s3 += wordlist[i] + ' '*(int(space/place)+2)
  21.                     for j in range(i+1,len(wordlist)):
  22.                         s3 += wordlist[j] + ' '*(int(space/place)+1)
  23.                 else:
  24.                     for i in range(len(wordlist)):
  25.                         s3 += wordlist[i] + ' '*(int(space/place)+1)
  26.             else:
  27.                 s3 = t3
  28.         output += s3 + '\n'
  29.     return output.strip()

  30. if __name__ == '__main__':
  31.     width = int(sys.argv[1])
  32.     output = adjust_txt(txt,width)
  33.     print(output)
复制代码


--------------------------------------------------------------------------------------------------------------------------------------------------------

使用了一个textwrap模块,完整代码如下:


  1. #!/bin/python
  2. #coding=utf-8
  3. import textwrap,sys

  4. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

  5. def adjust_txt(txt, width):
  6.     t1 = textwrap.fill(txt,width)
  7.     t2 = t1.split('\n')
  8.     output = ''
  9.     for t3 in t2:
  10.         wordlist = t3.split(' ')
  11.         space = width-len(t3)
  12.         place = len(wordlist) - 1
  13.         s3 = ''
  14.         if space > 0:
  15.             if space%place != 0:
  16.                 for i in range(space%place):
  17.                     s3 += wordlist[i] + ' '*(int(space/place)+2)
  18.                 for j in range(i+1,len(wordlist)):
  19.                     s3 += wordlist[j] + ' '*(int(space/place)+1)
  20.             else:
  21.                 for i in range(len(wordlist)):
  22.                     s3 += wordlist[i] + ' '*(int(space/place)+1)
  23.         else:
  24.             s3 = t3
  25.         output += s3 + '\n'
  26.     return output.strip()

  27. if __name__ == '__main__':
  28.     width = int(sys.argv[1])
  29.     output = adjust_txt(txt,width)
  30.     print(output)
复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
jerryxjr1220 + 5 + 5 + 2 答题奖励,如果width=20,你的程序还正确吗.

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-9 00:12:21 | 显示全部楼层
def adjust_txt(txt, width):
    list1=list(txt)
    t=0
    x=0
    while x<len(list1)/width-1:
        for i in range(t,t+width) :
            print(list1[i],end="")
            t+=1
        print()
        x += 1
    for r in range(t, len(list1)):
        print(list1[r], end="")
写的比较复杂,初学者,望多指教

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
jerryxjr1220 + 5 + 5 + 2 答题奖励,不过你的程序输出不对哦,请重新.

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-9 13:01:31 | 显示全部楼层
本帖最后由 小剑剑 于 2017-8-10 17:30 编辑
  1. txt = '''Hot work is one of the typical high risk work in work shop,
  2. if out of control, it will cause tragedy. We manage our hot work basing on
  3. the FM hot work permit system. Then, to make sure the fire risk are
  4. eliminated before we start hot work, what should we do? Please refer
  5. to this week's topic, hot work permit.'''

  6. def adjust_txt(t,m):
  7.     words=t.split()
  8.     l=list(map(len,words))
  9.     print(l)
  10.     le=len(l)
  11.     i=0
  12.     j=0
  13.     temp=0
  14.     while i<le:
  15.         temp+=l[i]+1# include blank
  16.         i+=1
  17.         if temp>m:
  18.             if temp==m+1:
  19.                 for k in range(i-j-1):
  20.                     words[j+k]+=" "
  21.                 words[i-1]+='\n'
  22.                 temp=0
  23.                 j=i
  24.             else:
  25.                 temp-=l[i-1]+2
  26.                 r=m-temp
  27.                 if i-j-2==0:#only one word
  28.                     words[j]+='\n'
  29.                     j+=1
  30.                     i=j
  31.                     temp=0
  32.                 else:
  33.                     x=r//(i-j-2)
  34.                     d=r%(i-j-2)
  35.                     for k in range(d):
  36.                         words[j+k]+=" "*(2+x)
  37.                     for k in range(i-j-d-2):
  38.                         words[j+k+d]+=" "*(x+1)
  39.                     words[i-2]+='\n'
  40.                     temp=0
  41.                     i-=1
  42.                     j=i
  43.     if 1<i-j:
  44.         temp-=1
  45.         r=m-temp
  46.         x=r//(i-j-1)
  47.         d=r%(i-j-1)
  48.         for k in range(d):
  49.             words[j+k]+=" "*(2+x)
  50.         for k in range(i-j-d):
  51.             words[j+k+d]+=" "*(x+1)
  52.     return "".join(words)

  53. print(adjust_txt(txt,16))
复制代码

评分

参与人数 1贡献 +1 收起 理由
jerryxjr1220 + 1 当width&amp;lt;=16的时候,你的程序还正确吗?

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-9 15:48:16 | 显示全部楼层
本帖最后由 小Q学Python 于 2017-8-10 09:24 编辑
  1. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

  2. def adjust_txt(txt, width):
  3.     output = ''  # 输出
  4.     flag = 1  # 标识是否处理完毕
  5.     while flag:
  6.         if len(txt) <= width:  #表示将处理最后一样
  7.             flag = 0
  8.             temp = txt
  9.         else:
  10.             index = txt[:width+1].rfind(' ')  # 找右边第一个空格
  11.             temp = txt[:index].rstrip()  # 即将处理的
  12.             txt = txt[index+1:].lstrip()  # 待下次循环时处理
  13.         add = width - len(temp)  # 需要增加的空格
  14.         if add == 0:  # 表示不需要增加空格
  15.             output += temp+'\n'
  16.         else:
  17.             counts = temp.count(' ')  # 超出字符中有多少空格
  18.             if counts == 0:  # 防止字符中只有一个单词,做填充处理
  19.                 #output += temp+' '*add+'\n'
  20.                 output += temp+'\n'  #  没注意这句,想当然的填充了空格。。若某一行只容得下一个单词,则该行按照左对齐格式输出,行尾同样不需要用空格填充
  21.                 continue
  22.             ans = (counts+add)//counts+1  # 填充空格
  23.             ys = (counts+add)%counts
  24.             for i in temp.split(' '):
  25.                 if ys == 0:
  26.                     ans -= 1
  27.                 output += i + ' '*ans
  28.                 ys -= 1
  29.             output = output.strip()+'\n'
  30.     return output[:-1]

  31. output = adjust_txt(txt,30)
  32. print(output)
复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
jerryxjr1220 + 5 + 5 + 2 答题奖励,当width=15的时候,你的程序还正.

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-9 16:15:43 | 显示全部楼层
本帖最后由 python911 于 2017-8-9 16:18 编辑

import re
txt = "Hot worrk is one of the 'typical' high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

def adjust_txt(txt,width=30):
    # txt1=txt.split(" ")
    # changdu=0
    hanglist=[]      #存放每行的显示字符串

    while len(txt)>width:

        if txt[width]==' ':   #判断第width个字符是否为' '

            txt=txt[:width]+'\n'+txt[(width+1):]   #将' '替换为'\n'
            txt=txt.split('\n')  #分割成列表
            hang=txt.pop(0)    #取列表第一项,即第一行,存放入列表
            hanglist.append(hang)
            txt=txt[0]   #将剩下的一大串再变身为txt
            
        else:
            geshu=0
            geshulist=re.findall(r'(?<=\S) (?=\S)',txt[:width])  #正则表达式不多说
            geshu=len(geshulist)   #得到当行' '的个数

            n=0
            while txt[width]!=' ' and n<=geshu:   #当第width个字符不为' ',且替换的个数不大于' '数
                txt=re.sub(r'(?<=\S) (?=\S)','  ',txt,1)  #一个空格,替换为两个空格,替换一次
                n+=1

            n=0
            while txt[width]!=' ' and n<=geshu:   #当所有一个空格都被替换成了两个空格,还没把那个长单词挤出去,则需考虑两个空格换为三个空格

                txt=re.sub(r'(?<=\S)  (?=\S)','   ',txt,1)
                n+=1   

            n=0
            while txt[width]!=' ' and n<=geshu:    #再加一个吧,三个空格换成四个,绝对够用了

                txt=re.sub(r'(?<=\S)   (?=\S)','    ',txt,1)
                n+=1   


            txt=txt[:width]+'\n'+txt[(width+1):]   #同上,取出第一行,剩余的再转成txt
            txt=txt.split('\n')
            hang=txt.pop(0)
            hanglist.append(hang)
            txt=txt[0]  
            
    hanglist.append(txt)   #将最后一行,也要加入
    result=''
    for line in hanglist:    #输出每一行
        result+=line+"\n"
    return result      

output = adjust_txt(txt)
print(output)






###重在参与,共同学习,还有点小问题,就这样交卷吧###


QQ截图20170809161757.png

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
冬雪雪冬 + 5 + 5 + 2 鼓励一下

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-9 17:37:10 | 显示全部楼层
import re
txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

def adjust_txt(txt, width):
    x,x1='',''
    i = 0
    y = 0
    z = 0
    list_index =0
    value = re.compile('\w')
    while i< len(txt):      #判断长度循环  
        if width+int(i) <= len(txt):       #截取长度
            list1 = txt[len(txt[:width+int(i)])] #转为list取下标
            list_index = width+int(i)   
            if txt[list_index+1] == ' ':
                list_index = width+int(i)+1
            else:
                while value.match(list1): #下标为字母循环向前找不为字母的下标
                    i=i-1
                    list1 = txt[len(txt[:width+int(i)])]
                    list_index = width+int(i)
            list2=list(txt[y:list_index].lstrip())
            if len(list2)==width:
                x1 = ''.join(list2)
            else:
                f = 0
                while len(list2)< width:  #填充空格
                    if ' 'in list2[f:]:
                        r =  list2[f:].index(' ')
                    else:
                        f = 0
                        z = z+1
                        r =  list2[f:].index(' ')
                    list2.insert(r+f,' ')
                    f=f+r+z+2
                    x1 = ''.join(list2)
            x1 = ''.join(list2)
            x=x+x1+'\n'            
        else:
            list1 = txt[len(txt)-1]
            i=len(txt)-width
            list_index = i + width
            list2=list(txt[y:list_index].lstrip())
            if len(list2)==width:
                x1 = ''.join(list2)
            else:
                f = 0
                while len(list2)< width:
                    if ' 'in list2[f:]:
                        r =  list2[f:].index(' ')
                    else:
                        f = 0
                        z = z+1
                        r =  list2[f:].index(' ')
                    list2.insert(r+f,' ')
                    f=f+r+z+2
                    x1 = ''.join(list2)
            x1 = ''.join(list2)
            x=x+x1+'\n'  
        y=list_index
        i=i+width
    return x


output = adjust_txt(txt, 30)
print(output)





#新人,重在参与,写的有点啰嗦

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
冬雪雪冬 + 5 + 5 + 2

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-9 20:16:52 | 显示全部楼层
txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

def adjust_txt(txt, width):
    output=""
    fuhao=",.?:'"               #定义标点符号字符串
    i=0
    while i<len(txt):
        
        line=""                 #定义字符串存放行信息   
        line=txt[i:i+width]     #从文件中获取指定宽度的一行信息   
        if (txt[i+len(line)-1].isalpha() and (txt[i+len(line)].isalpha() or  txt[i+len(line)] in fuhao) ) or txt[i+len(line)-1] =="'":            
            Nextline_start=i+line.rfind(" ")    #当下一行起始字符异常时, 获取line字符串最后一个空格
            line=txt[i:Nextline_start]          #将line字符串截短,重新赋值
            i=Nextline_start                    #将i 重新赋值,标记下一行开始
        else:
            line=txt[i:i+width]                 #当下一行起始字符符合规则时
            i=i+width                           #标记下一行开始
            
        if " " not in line:                     #行信息获取完毕后如果只有一个单词
            line.ljust()                        #单个词左对齐
        else:                    
            line=line.strip()                   #正常行删除行首和行尾的空格
      
        cycle=1                                 #左右对齐 对不足宽度的行使用空格进行填充,为了保证空格尽可能均匀分布到单词与单词之间,采用循环的方式
        while len(line)<width:
            j=0
            while j<len(line)-1:
                if len(line)>=width:            #宽度达到width 退出填充
                        break
                elif line[j:j+cycle]==" "*cycle:  #第一轮由单个空格(" ")扩充成俩个空格("  "), 第二轮对俩个空格("  ")扩充成三个空格("   ")
                        line=line[:j]+" "+line[j:]
                        j+=1+cycle
                else:
                        j+=1            
            cycle+=1
        output=output+line+"\n"   
    return output

output = adjust_txt(txt, 30)
print(output)

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
冬雪雪冬 + 5 + 5 + 2

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-10 11:43:25 | 显示全部楼层
本帖最后由 小锟 于 2017-8-11 10:16 编辑

  1. def adjust_txt(txt ,width ):
  2.     len_txt = len(txt)
  3.     list1 , i = [] , 0
  4.     #  先将字符串按照width输出,但不考虑加空格
  5.     while i + width <= len_txt:
  6.         j = 0
  7.         if txt[ i + width ] == ' ':
  8.             list1.append(txt[i : i + width])
  9.         else:   
  10.             while txt[ i + width - j ] != ' ':
  11.                 j += 1
  12.                 if j >= width:
  13.                     j = -1
  14.                     list1.append( txt[i:i + width - j])   
  15.                     break               
  16.             else :
  17.                 list1.append(txt[i : i + width - j])
  18.         i += width - j
  19.     list1.append( txt[i:])   
  20.     list1 = [i.strip() for i in  list1]
  21.     #  将返回的list1加空格
  22.     #  记相差数为d,该局中中间空格数为n .
  23.     #  d // n 为每个n都要加的空格
  24.     #  d % n 为哪几个需要多加一点空格的
  25.     list3 = []
  26.     for i in list1:
  27.         list2 = []
  28.         count = 0
  29.         if len(i) < width :
  30.             diff = width - len(i)
  31.             for j , k in enumerate(i):
  32.                 if k == ' ' :
  33.                     list2.append(j)
  34.                     count += 1
  35.             if count != 0 :     
  36.                 beishu = diff // len(list2)
  37.                 mod = diff % len(list2)            
  38.                 listi = list(i)
  39.                 while mod :               
  40.                     listi[list2[mod - 1]] +=  ' '
  41.                     mod -= 1     
  42.                 for i in list2:
  43.                     listi[i] += beishu * ' '
  44.                 list3.append(listi)
  45.             else:
  46.                 list3.append(i)
  47.         else:
  48.             list3.append(i)        
  49.     list4 = [( ''.join(i) if type(i) == list else i) for i in list3 ]   
  50.     return print('\n'.join(list4))


复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +3 收起 理由
jerryxjr1220 + 5 + 5 + 3 答题奖励

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-10 14:52:35 | 显示全部楼层
10000000个赞
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-10 16:23:59 | 显示全部楼层
本帖最后由 凤凰0620 于 2017-8-10 16:50 编辑
  1. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

  2. def adjust_txt(txt, width):
  3.         a = txt.split()
  4.         b=[]
  5.         for i in a:
  6.                 b.append(i)
  7.                 b.append(' ')
  8.         b.pop()

  9.          
  10.         #以width为行宽上限添加换行符,并去掉首尾空格
  11.         c = []
  12.         count = 0

  13.         for i in range(len(b)):
  14.             if (count + len(b[i])) <= width:
  15.                 c.append(b[i])
  16.                 count += len(b[i])
  17.             else:
  18.                 c.append('\n')
  19.                 count = 0
  20.                 c.append(b[i])
  21.                 count+=len(b[i])

  22.         try:
  23.             for i in range(len(c)):
  24.                 if c[i] == '\n':
  25.                     if c[i-1] == ' ':
  26.                         c.pop(i-1)    #因为换行符插入到单词之间,而单词之间被加入了空格,所以换行符旁边有且只有一个空格,要么在左要么在右
  27.                     else:
  28.                         c.pop(i+1)
  29.         except IndexError:
  30.             None


  31.         output = '' #初始化最终输出的字符串

  32.         #以空格均匀填充每行单词之间的间隙

  33.         d=''
  34.         for i in c:
  35.             d+=i
  36.             
  37.         e = d.split('\n')
  38.         
  39.         for each in e:
  40.             #print('共%d个字节' % len(each))
  41.             #print('有%d个空' % (len(each.split())-1))
  42.             #print('缺%d个空格' % (width-len(each)))
  43.             split_string = each.split() #按空格拆分
  44.             space_dict = {i:0 for i in range(len(split_string)-1)} #建立间隙字典
  45.             #计算每个间隙隙应填充几个空格
  46.             new_string = ''
  47.             count_space = width - len(each)
  48.             if count_space >= len(split_string):#如果应补空格数大于等于间隙数量
  49.                 while count_space >= len(split_string):
  50.                     for i in range(len(space_dict)):
  51.                         space_dict[i] +=1
  52.                     count_space -= len(space_dict)
  53.                 for i in range(count_space):
  54.                     space_dict[i] += 1
  55.             else: #应补空格数小于等于空隙数量
  56.                 for i in range(count_space):
  57.                     space_dict[i] += 1
  58.             #根据字典填充空格
  59.             new_each =[]
  60.             for i in range(len(space_dict)):
  61.                 new_each.append(split_string[i])
  62.                 new_each.append(' '*(space_dict[i]+1))
  63.             new_each.append(split_string[-1])

  64.             for each in new_each:
  65.                 new_string += each
  66.             output += (new_string + '\n')

  67.         return output

  68. output = adjust_txt(txt, 30)
  69. print(output)
复制代码



以下是经过正式变量命名的,根据个人习惯,看喜欢那种吧,第一种更简洁,第二种更正式

  1. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

  2. def adjust_txt(txt, width):
  3.         words_list = txt.split()
  4.         word_space = []
  5.         for i in words_list:
  6.                 word_space.append(i)
  7.                 word_space.append(' ')
  8.         word_space.pop()

  9.          
  10.         #以width为行宽上限添加换行符,并去掉首尾空格
  11.         lines_list = []
  12.         count = 0

  13.         for i in range(len(word_space)):
  14.             if (count + len(word_space[i])) <= width:
  15.                 lines_list.append(word_space[i])
  16.                 count += len(word_space[i])
  17.             else:
  18.                 lines_list.append('\n')
  19.                 count = 0
  20.                 lines_list.append(word_space[i])
  21.                 count+=len(word_space[i])

  22.         try:
  23.             for i in range(len(lines_list)):
  24.                 if lines_list[i] == '\n':
  25.                     if lines_list[i-1] == ' ':
  26.                         lines_list.pop(i-1)   #因为换行符插入到单词之间,而单词之间被加入了空格,所以换行符旁边有且只有一个空格,要么在左要么在右
  27.                     else:
  28.                         lines_list.pop(i+1)
  29.         except IndexError:
  30.             None


  31.         output = '' #初始化最终输出的字符串

  32.         #以空格均匀填充每行单词之间的间隙

  33.         pre_output=''
  34.         for i in lines_list:
  35.             pre_output += i
  36.             
  37.         fin_lines = pre_output.split('\n')
  38.         
  39.         for each in fin_lines:
  40.             #print('共%d个字节' % len(each))
  41.             #print('有%d个空' % (len(each.split())-1))
  42.             #print('缺%d个空格' % (width-len(each)))
  43.             split_string = each.split() #按空格拆分
  44.             space_dict = {i:0 for i in range(len(split_string)-1)} #建立间隙字典
  45.             #计算每个间隙隙应填充几个空格
  46.             new_string = ''
  47.             count_space = width - len(each)
  48.             if count_space >= len(split_string):#如果应补空格数大于等于间隙数量
  49.                 while count_space >= len(split_string):
  50.                     for i in range(len(space_dict)):
  51.                         space_dict[i] +=1
  52.                     count_space -= len(space_dict)
  53.                 for i in range(count_space):
  54.                     space_dict[i] += 1
  55.             else: #应补空格数小于等于空隙数量
  56.                 for i in range(count_space):
  57.                     space_dict[i] += 1
  58.             #根据字典填充空格
  59.             new_each =[]
  60.             for i in range(len(space_dict)):
  61.                 new_each.append(split_string[i])
  62.                 new_each.append(' '*(space_dict[i]+1))
  63.             new_each.append(split_string[-1])

  64.             for each in new_each:
  65.                 new_string += each
  66.             output += (new_string + '\n')

  67.         return output

  68. output = adjust_txt(txt, 30)
  69. print(output)
复制代码


评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
冬雪雪冬 + 5 + 5 + 2

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-10 17:31:12 | 显示全部楼层
bug 以修正
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-10 22:32:24 | 显示全部楼层
  1. txt = "Hot work is one of the typical high risk work in work shop, \
  2. if out of control, it will cause tragedy. We manage our hot \
  3. work basing on the FM hot work permit system. Then, to make \
  4. sure the fire risk are eliminated before we start hot work, \
  5. what should we do? Please refer to this week's topic, hot work permit."


  6. def adjust_txt(txt, width):
  7.     words = txt.split(" ")
  8.     line = ''
  9.     output = ''
  10.     line_list = []
  11.     a = 0
  12.     for inx, word in enumerate(words):
  13.         
  14.         if (a+len(word)) <= width:
  15.             a += len(word)
  16.             a += 1
  17.             line_list.append(word)
  18.             if (inx+1) == len(words):
  19.                 line = ' '.join(line_list)
  20.                 while len(line) < width:
  21.                     line = line.replace(' ', '  ', (width-len(line)) )
  22.                 output += line
  23.             continue
  24.         line = ' '.join(line_list)
  25.         while len(line) < width:
  26.             line = line.replace(' ', '  ', (width-len(line)))
  27.         output += line
  28.         output += '\n'
  29.         line_list = []
  30.         line_list.append(word)
  31.         a = len(word) + 1


  32.     return output

  33. output = adjust_txt(txt, 30)
  34. print(output)
复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
冬雪雪冬 + 5 + 5 + 2

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-10 23:11:22 | 显示全部楼层
本帖最后由 zhengod 于 2017-8-10 23:49 编辑
  1. import textwrap

  2. txt = "  Hot work is one of the typical  high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."

  3. def adjust_txt(txt, width):
  4.     s = textwrap.fill(textwrap.dedent(txt),width)
  5.     #print(s)
  6.     output =[]
  7.     for i in s.split('\n'):
  8.         #判断该行是否符合width
  9.         d = width - len(i)
  10.         #不符合的执行如下代码实现两端对齐
  11.         if d > 0:
  12.             a = i.split(' ')
  13.             da = len(a)-1
  14.             if da == 0:
  15.                 output.append(' '.join(a))
  16.                 continue
  17.             t = d // da
  18.             tt = d % da
  19.             #最后一个单词不处理
  20.             for k in range(da):
  21.                 if k <= tt-1:
  22.                     a[k] =a[k]+' '
  23.                 a[k] = a[k]+t*' '
  24.             
  25.             output.append(' '.join(a))
  26.             
  27.     output ='\n'.join(output)               
  28.     return output

  29. output = adjust_txt(txt, 30)

  30. print(output)

复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
冬雪雪冬 + 5 + 5 + 2

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-21 13:23:59 | 显示全部楼层
  1. def list_add(a, x):
  2.     for i in range(len(a)):
  3.         a[i] += x
  4.     return a

  5. def findall(a, b):
  6.     index = [ ]
  7.     i = 0
  8.     for each in a:
  9.         if each == b:
  10.             index.append(i)
  11.         i += 1
  12.     return index

  13. def add_space(temp, j):
  14.     a = findall(temp, ' ')
  15.     if len(a) == 0:
  16.         return temp
  17.     m = j//len(a)
  18.     n = j%len(a)
  19.     for k in range(len(a)):
  20.         if k + 1 <= n:
  21.             temp = temp[:a[k]] + (m+1)*' ' + temp[a[k]:]
  22.             a = list_add(a, m+1)
  23.         else:
  24.             temp = temp[:a[k]] + m*' ' + temp[a[k]:]
  25.             a = list_add(a, m)
  26.     return temp

  27. def adjust(txt, width):
  28.     new_txt = ''
  29.     while len(txt) > width:
  30.         temp = txt[:width+1]
  31.         if temp[-1] == ' ':
  32.             new_txt = new_txt + temp[:width] + '\n'
  33.             txt = txt[width+1:]
  34.         else:
  35.             i = temp.rindex(' ')
  36.             temp = temp[:i]
  37.             j = width - i
  38.             temp = add_space(temp, j)
  39.             new_txt = new_txt + temp[:width] + '\n'
  40.             txt = txt[i+1:]
  41.     if txt.count(' ') == 0:
  42.         new_txt = new_txt + txt + '\n'
  43.     if txt.count(' ') > 0:
  44.         a = findall(txt, ' ')
  45.         j = width - len(txt)
  46.         txt = add_space(txt, j)
  47.         new_txt = new_txt + txt + '\n'
  48.     return new_txt

  49. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."
  50. width = 30
  51. new_txt = adjust(txt, width)
  52. print(new_txt)
复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +2 收起 理由
jerryxjr1220 + 5 + 5 + 2 答题奖励,虽然已经过期了

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-6-22 18:26:15 | 显示全部楼层
本帖最后由 凌九霄 于 2018-6-22 20:17 编辑
  1. txt = "Hot work is one of the typical high risk work in work shop, if out of control, it will cause tragedy. We manage our hot work basing on the FM hot work permit system. Then, to make sure the fire risk are eliminated before we start hot work, what should we do? Please refer to this week's topic, hot work permit."


  2. def adjust_txt(txt, width):
  3.     txtlst = txt.split(' ')
  4.     output = ''
  5.     tmp = ''
  6.     i = 1
  7.     while len(txtlst) > 0:
  8.         while len(tmp) < width:
  9.             tmp = ' '.join(txtlst[:i])

  10.             if len(tmp) > width:
  11.                 tmp = ' '.join(txtlst[:i - 1])
  12.                 break
  13.             if txtlst[:i - 1] == txtlst[:]:
  14.                 break
  15.             else:
  16.                 i += 1

  17.         txtlst = txtlst[i - 1:]
  18.         poor = width - len(tmp)
  19.         tmplst = tmp.split(' ')

  20.         if len(tmplst) != 1 and poor > 0:
  21.             while poor > 0:
  22.                 for j in tmplst[:-1]:
  23.                     if poor > 0:
  24.                         tmplst[tmplst.index(j)] += ' '
  25.                         poor -= 1
  26.                     else:
  27.                         break
  28.         output += ' '.join(tmplst) + '\n'
  29.         tmp = ''
  30.         i = 1
  31.     return output
复制代码

   
width = 20
  1. Hot  work  is one of
  2. the   typical   high
  3. risk  work  in  work
  4. shop,   if   out  of
  5. control,   it   will
  6. cause   tragedy.  We
  7. manage  our hot work
  8. basing on the FM hot
  9. work  permit system.
  10. Then,  to  make sure
  11. the  fire  risk  are
  12. eliminated before we
  13. start hot work, what
  14. should we do? Please
  15. refer to this week's
  16. topic,    hot   work
  17. permit.
复制代码


width = 30
  1. Hot work is one of the typical
  2. high  risk  work in work shop,
  3. if  out  of  control,  it will
  4. cause  tragedy.  We manage our
  5. hot  work basing on the FM hot
  6. work  permit  system. Then, to
  7. make  sure  the  fire risk are
  8. eliminated before we start hot
  9. work,   what   should  we  do?
  10. Please  refer  to  this week's
  11. topic,    hot   work   permit.
复制代码


width = 50
  1. Hot  work  is one of the typical high risk work in
  2. work  shop,  if  out  of  control,  it  will cause
  3. tragedy.  We  manage our hot work basing on the FM
  4. hot  work  permit  system.  Then, to make sure the
  5. fire risk are eliminated before we start hot work,
  6. what  should  we  do?  Please refer to this week's
  7. topic,          hot          work          permit.
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 08:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表