python - 每 64 个字符插入换行符

标签 python regex string python-3.x

有人能指出我在这方面的正确方向吗?

我有一个包含单词句子的字符串 例如“他试图学习 Pythonic 或正则表达式来解决他的问题”

有问题的字符串非常大,我需要将其分成多行,每行不能超过 64 个字符。 但我不能每 64 个字符插入一个换行符。我需要确保中断发生在第 64 个字符之前最接近的字符(一组字符),以确保该行不超过 64 个字符。 例如我只能在空格、逗号或句号后插入换行符

我还需要非常高效的解决方案,因为它是一个会发生很多很多次的操作。

使用文本换行

我不确定 textwrap 是解决我的问题的方法,因为我需要保留输入字符串中的原始换行符。 示例:

long_str = """
123456789 123456789 123456789 123456789 123456789 123456789
Line 1: Artificial intelligence (AI), sometimes called machine intelligence, 
Line 2: is intelligence demonstrated by machines, 
Line 3: in contrast to the natural intelligence displayed by humans and  other animals. 
Line 4: In computer science AI research is defined as
"""
lines = textwrap.wrap(long_str, 60, break_long_words=False)
print('\n'.join(lines))

我想要的是这样的:

123456789 123456789 123456789 123456789 123456789 123456789
Line 1: Artificial intelligence (AI), sometimes called 
machine intelligence, 
Line 2: is intelligence demonstrated by machines, 
Line 3: in contrast to the natural intelligence displayed 
by humans and other animals. 
Line 4: In computer science AI research is defined as

但是 textwrap 给了我这个:

 123456789 123456789 123456789 123456789 123456789 123456789
Line 1: Artificial intelligence (AI), sometimes called
machine intelligence,  Line 2: is intelligence demonstrated
by machines,  Line 3: in contrast to the natural
intelligence displayed by humans and other animals.  Line 4:
In computer science AI research is defined as

我怀疑正则表达式可能是答案,但我无法用正则表达式解决这个问题。

最佳答案

在换行符上将长字符串拆分为单独的行。 “像往常一样”包裹每个单独的行,然后再次将所有内容连接到单个字符串。

import textwrap

long_str = """
123456789 123456789 123456789 123456789 123456789 123456789
Line 1: Artificial intelligence (AI), sometimes called machine intelligence, 
Line 2: is intelligence demonstrated by machines, 
Line 3: in contrast to the natural intelligence displayed by humans and  other animals. 
Line 4: In computer science AI research is defined as
"""

lines = []
for line in long_str.split('\n'):
    lines += textwrap.wrap(line, 60, break_long_words=False)
print('\n'.join(lines))

由于 textwrap 返回字符串列表,因此您无需执行任何其他操作,只需继续将它们粘贴在一起并在末尾连接它们即可。

关于python - 每 64 个字符插入换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53164077/

相关文章:

Python httplib.HTTPSConnection 超时——连接与响应

Maya 和其他 3d 应用程序的 python 版本

string - 在 Swift 中比较时间字符串

c++ - 使用指针处理字符串

python - Flask + Flask-Security + Babel 不工作

python - 鸭子类型(duck typing)实践 - Python 3.7

c# - 使用正则表达式模式查找列表中是否存在项目

Java如何仅更改字段分隔符而不更改实际数据

python - 正则表达式子函数不适用于 unicode 字符串

java - 我在递归地实现 String 的子字符串方法时遇到问题