如何在Python中删除文本中的空行?

2024-07-07 08:49:15 发布

您现在位置: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(),但它们对文本没有任何作用。这有什么不起作用的原因吗?我希望代码是一个单行程序或者我可以保存为变量的东西,因为我以后需要结果。这是一个更大项目的一部分,我无法通过


Tags: ofthenoinprojectuseitat
3条回答

您需要避免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)
text=open("sample.txt")
print(' '.join([line.strip() for line in text]))

也可以使用变量保存值并打印,而不是直接打印

single = ' '.join([line.strip() for line in text])
print (single)

可以通过将换行符替换为空格来执行此操作:

string=string.replace("\n\n"," ")

或者使用.splitlines(),然后将它们重新连接在一起:

stringlist=string.splitlines()
string= " ".join(stringlist)

注意:在第一个示例中,我用空格替换了每两个换行符,因为示例中有两个换行符分隔每一行。如果每行只有一个换行符,请使用“\n”

相关问题 更多 >