Я еще не могу прокомментировать (начало работы на сайте), но добавил более общую версию производного класса Джерри Коффина в класс. К тому же
Спасибо Джерри за супер идею.
(потому что он должен быть проверен экспертами, добавив его здесь слишком временно)
struct SeparatorReader: std::ctype<char>
{
template<typename T>
SeparatorReader(const T &seps): std::ctype<char>(get_table(seps), true) {}
template<typename T>
std::ctype_base::mask const *get_table(const T &seps) {
auto &&rc = new std::ctype_base::mask[std::ctype<char>::table_size]();
for(auto &&sep: seps)
rc[static_cast<unsigned char>(sep)] = std::ctype_base::space;
return &rc[0];
}
};
Я думаю, что это код, который вам нужен. дайте мне знать, если я ошибаюсь.
import numpy as np
def dataLoad(filename):
#opening and reading the data file
file=open(filename,'r').readline()
#creating the numpy matrix object
data=np.matrix(file)
print('raw data:',data)
#checking the conditions
#... for first column
i=0
while(i<len(data)):
if data.item(i,0)<10 or 60<data.item(i,0):
print('error message')
print('removed',data[i])
data=np.delete(data,(i),axis=0)
else:
i+=1
print('data after checking 1st condition:',data)
#... for second column
i=0
while(i<len(data)):
if data.item(i,1)<0:
print('error message')
print('removed',data[i])
data=np.delete(data,(i),axis=0)
else:
i+=1
print('data after checking the 2nd condition:',data)
#... for third column
i=0
while(i<len(data)):
if data.item(i,2) not in (1,2,3,4):
print('error message')
print('removed',data[i])
data=np.delete(data,(i),axis=0)
else:
i+=1
print('data after checking the 3rd condition:',data)
return data
print(dataLoad('test.txt'))
это снова я :) этот код является фиксированной версией Edit 2 в описании вопроса:
data = open("test.txt", "r").readlines()
for raw_line in range(len(data)):
line = [int(n) for n in data[raw_line].split(' ')]# this splits the "1 2 3" to ['1','2','3'] and then, makes them integer([1,2,3])
if (line[0] < 10) or (line[0] > 60):
print("Temperature is out of range in row",raw_line)
elif (line[1]<0):
print("Growth rate is negative in row",raw_line)
elif (line[2]!=1) or (line[2]!=2) or (line[2]!=3) or (line[2]!=4):
print("Bacteria is not 1, 2, 3 or 4 in row",raw_line)
PS: я предполагаю, что каждая строка формата test.txt точно "abc" А, В и С являются числами. если он другой, дайте мне знать, чтобы это исправить
PPS: как вы знаете, этот код не удаляет недопустимые строки и просто печатает сообщения об ошибках
Я думаю, что ваша проблема в том, что вы не изменяете данные, как только условие выполнено. Что-то вроде приведенного ниже кода должно помочь решить вашу проблему:
import numpy as np
def dataLoad(filename):
data=np.loadtxt(filename)
retdata = []
for row in data:
if (row[0] < 10) or (row[0] > 60):
print("Temperature is out of range")
continue
elif (row[1]<0):
print("Growth rate is negative")
continue
elif (row[2]!=1) or (row[2]!=2) or (row[2]!=3) or (row[2]!=4):
print("Bacteria is not 1, 2, 3 or 4")
continue
retdata.append(row)
return retdata
Надеюсь, что поможет.