首页 > 解决方案 > 如何从 Python 中的文本中删除空行?

问题描述

这可能是一个简单的问题,但我刚开始使用 Python,不知道为什么这不起作用。我正在尝试从文本中删除空行,但似乎没有任何效果。

我有以下示例文本

The Project Gutenberg EBook of Alice in Wonderland, by Lewis Carroll

This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.org


Title: Alice in Wonderland

Author: Lewis Carroll

Illustrator: Gordon Robinson

Release Date: August 12, 2006 [EBook #19033]

Language: English

Character set encoding: ASCII

*** START OF THIS PROJECT GUTENBERG EBOOK ALICE IN WONDERLAND ***

我需要结果是一长串文本,如下所示:

The Project Gutenberg EBook of Alice in Wonderland, by Lewis Carroll This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever.  You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org Title: Alice in Wonderland Author: Lewis Carroll Illustrator: Gordon Robinson Release Date: August 12, 2006 [EBook #19033] Language: English Character set encoding: ASCII *** START OF THIS PROJECT GUTENBERG EBOOK ALICE IN WONDERLAND ***

我努力了

text=open("sample.txt","r")

for line in text:
    line = line.rstrip()
    print(line)

和 .strip() 也是如此,但它们对文本没有任何作用。这不起作用有什么原因吗?我希望代码是单行代码或可以保存为变量的代码,因为稍后我需要结果。这是一个更大项目的一部分,我无法超越这一点。

标签: pythontextstrip

解决方案


您需要避免 print() 的默认行为,即输出换行符。你实现如下: -

with open('sample.txt') as txtfile:
    for line in txtfile:
        print(line.strip(), end='')
    print()

对于这种特殊情况,您也可以这样做:-

with open('sample.txt') as txtfile:
  contents = txtfile.read().replace('\n', '')
  print(contents)

推荐阅读