【问题标题】:Python Insert new line if line has more than 50 characters如果行超过50个字符,Python插入新行
【发布时间】:2013-08-23 19:05:43
【问题描述】:

我一直试图找出 Python 上的一个问题,这让我疯狂了几个星期...... 我有一个包含大量文本的文本文件。有些行超过 50 个字符,这对我来说是个问题,因为它必须与文本框对齐。

我的问题是: 如果文本文件中的一行超过 50 个字符(包括空格),我如何设法插入新行 (\n)?

提前致谢。

【问题讨论】:

    标签: python string python-2.7 line newline


    【解决方案1】:

    为此有一个库。请尝试以下操作:

    import textwrap
    
    wrapped = textwrap.fill(YourText, 50)
    

    【讨论】:

    • 这种方法对我不起作用,因为即使只有 2 个字符的行,它也会每 50 个字符输入新行。
    • 以上假设YourText是一个单独的段落。
    【解决方案2】:

    这应该可以解决问题

    with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
      for line in infile:
        if len(line) > 50:
          outfile.write('\n'.join(line[i:i+50] for i in xrange(0,len(line), 50)))
        else:
          outfile.write(line)
    

    【讨论】:

    • 太棒了!谢谢!像魅力一样工作
    • 你用这种方式分词。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2015-09-25
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多