首页 > 解决方案 > 使用 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
'''

标签: python-3.xnumpy

解决方案


我认为您仍然可以使用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')

推荐阅读