V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
PanameraM
V2EX  ›  Python

大家帮忙看一道 python 题目,给个答案 谢谢!

  •  
  •   PanameraM · Nov 2, 2016 · 3419 views
    This topic created in 3465 days ago, the information mentioned may be changed or developed.

    编写一个程序, 在一个文本文件中查找长度大于 80 个字符的文本行. 从最接近 80 个字符的单词断行, 把剩余文件插入到下一行处. 程序执行完毕后, 应该没有超过 80 个字符的文本行了

    13 replies    2016-11-03 12:27:17 +08:00
    laoyuan
        1
    laoyuan  
       Nov 2, 2016
    整个用空格连起来重新排
    lrh3321
        2
    lrh3321  
       Nov 2, 2016
    ```
    line = '12345 ' * 20 #

    i,j = 0,0
    while i < 80:
    j = i
    i = line.find(' ',j + 1)
    print(line[:j])
    ```

    从最接近 80 个字符的单词断行
    neoblackcap
        3
    neoblackcap  
       Nov 2, 2016
    这样子格式化小心炸了
    Aliencn
        4
    Aliencn  
       Nov 2, 2016
    import random
    line='1'
    for a in range(100):
    line='{} {}'.format(line,'1' * random.randint(0,10))
    #print(line)

    line_list=[]
    a=80
    while True:
    if len(line) <= 80:
    line_list.append(line)
    break
    if line[a] != ' ':
    a-=1
    else:
    line_list.append(line[:a])
    while line[a] == ' ':a+=1
    line=line[a:]
    a=80

    for line in line_list:
    print('{},len={}'.format(line,len(line)))

    #从最接近 80 个字符的单词断行
    #程序执行完毕后, 应该没有超过 80 个字符的文本行了
    Aliencn
        5
    Aliencn  
       Nov 2, 2016
    哎呀,发出去就格式乱了,你凑合看吧
    PanameraM
        7
    PanameraM  
    OP
       Nov 2, 2016
    @thekoc thx
    PanameraM
        8
    PanameraM  
    OP
       Nov 2, 2016
    @Aliencn thx
    PanameraM
        9
    PanameraM  
    OP
       Nov 2, 2016
    @lrh3321 thx
    msg7086
        10
    msg7086  
       Nov 3, 2016   ❤️ 1
    从 str[80]开始向前找空格,找到以后切下来扔出去就行了。
    ruoyu0088
        11
    ruoyu0088  
       Nov 3, 2016
    看看 Python 的标准库 textwrap
    PanameraM
        12
    PanameraM  
    OP
       Nov 3, 2016
    @ruoyu0088 thx 有库就简单多了~
    qwer1234asdf
        13
    qwer1234asdf  
       Nov 3, 2016 via iPhone
    啊……这明明就是一个编辑器该干的事, gedit 设置,两分钟估计就解决了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4978 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 05:37 · PVG 13:37 · LAX 22:37 · JFK 01:37
    ♥ Do have faith in what you're doing.