python-3.x - 使用 numpy 进行文件操作
问题描述
我正在尝试使用 numpy 从文本文件中删除短语。我尝试使用 num = [] 和 num1.append(num1) 'a' 而不是 'w' 来写回文件。虽然追加不会删除短语 writes' 第一次运行删除短语第二次运行删除第二行不是短语第三次运行清空文件
import numpy as np
phrase = 'the dog barked'
num = 0
with open("yourfile.txt") as myFile:
for num1, line in enumerate(myFile, 1):
if phrase in line:
num += num1
else:
break
a=np.genfromtxt("yourfile.txt",dtype=None, delimiter="\n", encoding=None )
with open('yourfile.txt','w') as f:
for el in np.delete(a,(num),axis=0):
f.write(str(el)+'\n')
'''
the bird flew
the dog barked
the cat meowed
'''
解决方案
我认为您仍然可以使用nums.append(num1)
withw
模式,我认为您遇到的问题是您使用 1-index 而不是 numpy 数组中预期的 0-index 的行的enumerate
函数。myFile
将其从 更改enumerate(myFile, 1)
为enumerate(myFile, 0)
似乎可以解决问题
import numpy as np
phrase = 'the dog barked'
nums = []
with open("yourfile.txt") as myFile:
for num1, line in enumerate(myFile, 0):
if phrase in line:
nums.append(num1)
a=np.genfromtxt("yourfile.txt",dtype=None, delimiter="\n", encoding=None )
with open('yourfile.txt','w') as f:
for el in np.delete(a,nums,axis=0):
f.write(str(el)+'\n')
推荐阅读
- authentication - 尝试登录 prestashop 管理面板时遇到两个错误
- reactjs - 从列表中获取数据
- xamarin.forms - Xamarin.Forms:带有 ContentView 的可重用错误视图,如何设置图像源?
- python - 为什么这个 Beautiful Soup 代码不能解析我的目标文本?
- .net-core - 在 ef core 中的表设置中添加另一个外键
- azure - 将子域重定向到 Azure 应用服务中的子目录
- sql - 在连接条件下从同一个表中检索 2 个条目
- lotus-notes - (Domino Notes)如何将文档从原始 NSF 移动到另一个 NSF?
- c# - 每当在控制器/方法上使用 AuthorizeAttribute 时执行过滤器
- python - 如何检查从 sqlite2 执行返回的结果?