Python合并无空白换行的行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python合并无空白换行的行相关的知识,希望对你有一定的参考价值。

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

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('
'):
                line.replace('
', '')
                print(line)

感谢您的帮助。

答案

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

with open("data.txt") as f:
    for line in f.read().split("

"):
        print("".join(line.split("
")) + "
")

输出:

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:
        lines = [i.replace('
', '') for i in f_in.read().split('

')]

    # here you do something with your `lines`

以上是关于Python合并无空白换行的行的主要内容,如果未能解决你的问题,请参考以下文章

用于合并 Excel 中与其他列中的信息匹配的行的单元格的宏

删除/etc/fstab文件中所有以#开头,后面至少跟一个空白字符的行的行首的#和空白字符

python 怎么判断文件的空行

Python输出换行的两种方法

python怎么判断读取的是空行

excel如何提取所需关键字所在行?