python - 从文本文件 Python 3.3 中删除非数字字符

标签 python python-3.x

<分区>

我的任务是从文本文件中删除所有非数字字符,包括空格,然后在旧字符旁边打印新结果,例如:

之前:

sd67637 8

ssheiej44

之后:

sd67637 8 = 676378

ssheiej44 = 44

因为我是初学者,我不知道从哪里开始这项任务。我按照另一位用户的说明进行操作,但我不太清楚详细说明这是我目前所知道的。

text1 = open('/Users/student/Desktop/Harry.txt', 'r')
data = text1.readlines()
new_string = ''.join(ch for ch in data if ch.isdigit())
print(data, '=', new_string)

但它仍然没有给我如上所示的预期效果。相反,我得到这个:

    [] = 

请有人解决这个问题并用通俗易懂的术语解释一下。

最佳答案

您没有调用 text1.readlines 方法。添加():

data = text1.readlines()

请注意,text1 等文件对象可以用作迭代器。无需调用 .readlines();直接遍历 text1 。您的代码仍然需要调整; .readlines()text1 都给你一系列:

for line in text1:
     new_string = ''.join(ch for ch in line if ch.isdigit())
     print(data, '=', new_string)

在您的版本中,ch 一次被分配文件中的一整行,并且由于每行至少包含一个换行符,.isdigit() 将 < em>总是为假。

关于python - 从文本文件 Python 3.3 中删除非数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17337382/

相关文章:

python-3.x - 启动本地 flask 服务器以使用 pytest 进行测试

python-3.x - 在python pandas中,如何使用where条件使用外连接?

python - 列表中的一个值,python

python - Errno 13 - 文档文件夹中的权限被拒绝?

python - Django 表格 : cannot call form. 干净

python - 我如何在我的 Mac 上为 python 安装漂亮的汤?看到错误

python - 如何设置pandas中两列的值

python - 解析多个 "msg"文件并将正文存储在csv文件中

python - 如何迭代切片?

python - 线性回归模型