0
Follow
0
View

How does [Python] add newlines automatically

fyb3526642 注册会员
2023-02-25 13:07

The following answers are based on ChatGPT and GISer Liu:
Hello! Depending on your needs, you can use Python's string handlers to automatically add newlines.

  • 1. First, you can use Python's replace() function to replace the Spaces after commas and periods on each line with \n. The specific code is as follows:

    line = "这是一个测试,测试一下换行符的使用。"
    line = line.replace(", ", ",\n").replace(". ", ".\n")
    

    In the above code, we use the replace() function to replace the Spaces after each comma and period with \n.

  • 2. Next, you can use Python's string slicing to segment each line according to certain rules and add between each paragraph. The specific code is as follows: \n

line = "这是一个测试,测试一下换行符的使用。这是一个测试,测试一下换行符的使用。"
i = 0
while i < len(line):
    if i+16 < len(line) and (line[i+10:i+12] == ", " or line[i+10:i+12] == ". "):
        line = line[:i+12] + "\n" + line[i+12:]
        i += 13
    else:
        line = line[:i+14] + "\n" + line[i+14:]
        i += 15

In the above code, we use a while loop to walk through each character, slicing each line up in a certain way, and adding \n between each paragraph.

With the above code, you can automatically add a newline function.

douniwan710 注册会员
2023-02-25 13:07
img

< !- - - - - >
ctrl61 注册会员
2023-02-25 13:07

This answer quotes ChatGPT

This function splits the input text string, text, into lines and processes each line. Within each line, we use a loop to walk through each character and wrap the line according to the rules described above. Finally, the processed rows are reassembled into a string and returned.

Please note that this is a simple example implementation and you may need to modify it as appropriate. Hope to help you!

def auto_wrap(text):
    result = []
    for line in text.split('\n'):
        new_line = ''
        last_punc = -1
        for i, char in enumerate(line):
            if i - last_punc > 10 and i - last_punc <= 16 and char in ',.':
                new_line += line[last_punc+1:i+1] + '\n'
                last_punc = i
            elif i - last_punc > 16:
                new_line += line[last_punc+1:i] + '\n'
                last_punc = i - 1
        new_line += line[last_punc+1:] + '\n'
        result.append(new_line)
    return '\n'.join(result[:-1])


dfzxdmy110 注册会员
2023-02-25 13:07

The answer is partly GPT, GPT_Pro better solution
Python can use textwrap module to achieve line wrapping, specifically as follows:

First, import the textwrap module:

import textwrap
Then, define a string:
string = "这是一个字符串,超过10个字符需要换行"
Finally, use the textwrap.fill() function to wrap lines at the specified location:
string = textwrap.fill(string,width=10)

Then, the above string will wrap itself:

这是一个字符串,
超过10个字符需要换行 

In addition, there are other features in the textwrap module that greatly facilitate our work. For example, given a long text string, we can split it into multiple lines of text using the textwrap.fill() function:

long_string = "这是一个长文本字符串,它包含多行文本" 
long_string = textwrap.fill(long_string, width=8) 

yields multiline text of the form:

这是一个 
长文本 
字符串, 
它包含 
多行文本 

It is also possible to use the textwrap.indent() function for text alignment, indentation, and other formatting processes. For example:

long_string = "这是一个长文本字符串,它包含多行文本" 
long_string = textwrap.indent(long_string, '\t') 

gives you multiline text of the form:

    这是一个 
    长文本 
    字符串, 
    它包含 
    多行文本  

Similarly, there are other functions in the textwrap module that you can use to format text. For example, the textwrap.shorten() function can split the text into multiple parts and trim some of the content. Of course, it is also important to understand all the functions in the textwrap module and take full advantage of their capabilities to suit your job requirements.
If the answer is helpful, please accept it.

hainancyp 注册会员
2023-02-25 13:07

For your own ideas, you can use string slice-and-loop traversal methods to automatically add newlines. The specific code is as follows:

def auto_wrap(text):
    result = ""
    for i in range(0, len(text), 14):
        line = text[i:i+14]
        if len(line) >= 10 and len(line) <= 16:
            index = max(line.rfind(","), line.rfind("."))
            if index != -1:
                line = line[:index+1] + "\n" + line[index+1:]
        else:
            line = line + "\n"
        result += line
    return result

Usage:

text = "这是一段需要自动换行的文本,每行不超过14个字符。逗号和句号后面会自动添加换行符。"
result = auto_wrap(text)
print(result)

Output:

这是一段需要自动
换行的文本,每
行不超过14个字
符。逗号和句号
后面会自动添加
换行符。

Note: This code only considers the case of adding line breaks after commas and periods. If you need to consider other symbols or special needs, you can modify it accordingly.

About the Author

Question Info

Publish Time
2023-02-25 13:07
Update Time
2023-02-25 13:07

Related Question

关于导入#mtcnn#的问题,如何解决?(语言-python)

python封装显示等待,无法运行

python解题,如果编辑代码

“无法强制到系列,长度必须为1:给定11”错误在Python中意味着什么?

python分析中,csv文件表头检测不出来

python查错与问题解决

Python提交百度关键词显示网络不给力

中文小说词频分析,无法显示词云图,如何解决?(语言-python)

Python怎么能让count=3在第一行年份在第二个行

Python新手-试图理解我的代码哪里出错了