python - 如何从 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() 也是如此,但它们对文本没有任何作用。这不起作用有什么原因吗?我希望代码是单行代码或可以保存为变量的代码,因为稍后我需要结果。这是一个更大项目的一部分,我无法超越这一点。
解决方案
您需要避免 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)
推荐阅读
- docker - Docker 更新或从新构建
- java - 如何对可缓存方法进行单元测试
- oauth-2.0 - restsharp 和邮递员
- php - PHP MySQL表结果按日期排序
- amazon-cloudformation - cloudformation 堆栈更新和启动模板版本/自动缩放组的问题
- coq - Coq 中量词的德摩根定律
- python - 将图像文件夹从我的 PC 上传到 Google Colab
- python - 如何从 Django 中的每个用户那里获取最后一条消息?
- reporting-services - 如何根据 SQL DB 中条目值的变化触发自动生成报告?
- f# - 加入 2 个基于 f# 中相同标签的记录列表