python - 将字符串拆分为最大长度 X 的片段 - 仅在空格处拆分

标签 python algorithm python-3.x text

我有一个很长的字符串,我想将其分成最多 X 个字符的片段。但是,仅在一个空格处(如果字符串中的某个单词长于 X 个字符,则将其放入自己的部分)。

我什至不知道如何开始做这件事……用 Python 的方式

伪代码:

declare a list
while still some string left:
   take the fist X chars of the string
   find the last space in that
   write everything before the space to a new list entry
   delete everything to the left of the space

在我编写代码之前,是否有一些 python 模块可以帮助我(我认为 pprint 不能)?

最佳答案

使用 textwrap模块(它也会在连字符处中断):

import textwrap
lines = textwrap.wrap(text, width, break_long_words=False)

如果您想自己编写代码,我会采用以下方法:首先,将文本拆分为单词。从一行中的第一个单词开始,然后迭代剩余的单词。如果下一个单词适合当前行,则添加它,否则完成当前行并将该单词用作下一行的第一个单词。重复直到用完所有单词。

这是一些代码:

text = "hello, this is some text to break up, with some reeeeeeeeeaaaaaaally long words."
n = 16

words = iter(text.split())
lines, current = [], next(words)
for word in words:
    if len(current) + 1 + len(word) > n:
        lines.append(current)
        current = word
    else:
        current += " " + word
lines.append(current)

关于python - 将字符串拆分为最大长度 X 的片段 - 仅在空格处拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32122022/

相关文章:

python - 如何选择与我的模型相关的模型对象

python - Scikit learn - 如何使用 SVM 和随机森林进行文本分类?

Python 根本无法工作

javascript - 使用 Ajax 的 Django POST

c++ - 检测和调整负零

algorithm - 考虑 "belongingness"的集群相似曲线?

python - 归并排序Python实现方法

mysql - 我收到错误 "Unsupported lookup ' 图标包含 ' for CharField or join on the field not permitted."

c# - 在 C# 中优化算法和/或结构

forms - 使用flask wtform DateTimeField 的无效日期时间格式的自定义错误消息