Python合并无空白换行的行

问题描述 投票:2回答:2

我需要您解决以下问题。我有一些大的文本文件,例如:

This is the Name of the Person

This is his surname

He likes to sing 
every time.

我只想将He likes to sing行与every time.合并,因为在此之后我要对每个字符串进行其他正则表达式处理。

因此输出应为:

This is the Name of the Person

This is his surname

He likes to sing every time.

我很喜欢用:

for file in file_list:
    with open(file, 'r', encoding='UTF-8', errors='ignore') as f_in:
        for line in f_in:
              if not line.startswith('\n'):
                line.replace('\n', '')
                print(line)

感谢您的帮助。

python newline
2个回答
0
投票

您可以分割\n\n上的部分,然后通过分割\n来合并每个部分:

with open("data.txt") as f:
    for line in f.read().split("\n\n"):
        print("".join(line.split("\n")) + "\n")

输出:

This is the Name of the Person

This is his surname

He likes to sing every time.

0
投票

您可以尝试以下方法:

for file in file_list:
    with open(file, 'r', encoding='UTF-8', errors='ignore') as f_in:
        lines = [i.replace('\n', '') for i in f_in.read().split('\n\n')]

    # here you do something with your `lines`
© www.soinside.com 2019 - 2024. All rights reserved.