python中的表 - 有一些错误 - 不知道为什么

时间:2013-12-08 19:21:26

标签: python

我对python中的“技术”和基本功能有一些疑问。

我有一张这样的表:

Name,Gender,Age,Salary,Height
Menny,   M,    1,   1,   1
James,   J,    2,   2,   2
Sami,    S,    3,   3,   3


class Table:

def __init__(self,path,sep):
    try:
        f = open(path, "r")
        read_file = f.read()
        f.close()
    except:
        print "cannot create a table from this file"
        return

    table = read_file.split("\n")
    for i in range (len(table)):
        table[i] = table[i].split(sep)

    if len(table) > 0:
        for i in range(len(table[0])):
            if table[0][i] in table[0][0:i]:
                raise ValueError

        row_names = []
        for i in range(1,len(table)):
            if len(table[i]) != len(table[0]):
                raise ValueError
            if table[i][0] in row_names:
                raise ValueError
            row_names.append(table[i][0])

现在我想使用功能:  1.知道有多少个细胞。我有12个细胞。表的高度为len(表)。然后宽度为len(表[0])。单元格的数量是高度*宽度。 这样:

    def len(self):
        height = len(table)
        width = len(table[0])
      return height * width

如果我试过这个:

def len(self):
    len(self.nestedList)*len(self.nestedList[0])

我得到“无”

  1. 如果在shell中我写了名字Menny,Sami等,那么打印其余部分(年龄,工资等).... 所以我想到了:

    def the_row (self, rowname):
    rows_checking = []
    for i in range(1, len(table)):
        rows_checking.append(table[i])
        if rowname in rows_checking:
            table[i].remove(table[0:0])
            return table[i]
    
    1. 和第二个任务几乎一样,但这次函数会打印2个常用的值。例如 - 如果我写Menny和Age,代码将打印“1”。 再说一次,我想我会像在前任务中那样做,但这一次:
    2. get_the_value(个体,rowname,colname的)

      到目前为止似乎是好主意,我希望如此...... 但我得到错误:

      AttributeError: Table instance has no attribute '__len__'
      

      AttributeError: Table instance has no attribute 'len'
      

      可能是因为我没有在这里使用“自我”,对吧?那我该怎么办? 你不必用勺子喂我,告诉我应该的代码,但请尽可能给我建议。

      编辑代码:

      class Table:
      
      def __init__(self,path,sep):
          self.path=path
          self.sep=sep
          self.g=[]
          self.count=0
          self.headlines=[]
          self.matrix=[]
          self.headrows=[]
          self.postionrow=0
          self.postioncolmn=0
          try:
              f=open(self.path,'r')
      
              read_file=f.read()
              split_file=read_file.split()
              for line in split_file:
                  list_the_line=line.split(self.sep)
                  self.g.append(list_the_line)
              self.count=0    
              for z in range (len(self.g[0])):
                  self.count=0 
                  for d in range(len(self.g[0])):
                      if self.g[0][z]==self.g[0][d]:
                          self.count+=1
                  if self.count>=2:
                      raise ValueError        
      
      
      
      
              num_first_line=len(self.g[0])
              for k in range (len(self.g)):
                  if len(self.g[k])!= num_first_line:
                      raise ValueError
      
              self.headlines=self.g[0]        
              self.g.remove(self.g[0])
      
              self.count=0
              for row_name1 in range (len(self.g)):
                  self.count=0
                  for row_name2 in range(len(self.g)):
                      if self.g[row_name1][0]==self.g[row_name2][0]:
                          self.count+=1
      
                  if self.count>=2:
                      raise ValueError
      
      
      
      
      
      
      
              for i in range (len(self.g)):
                  self.headrows.append(self.g[i][0])
                  self.g[i].remove(self.g[i][0])
      
              ezer=[]
      
              for op in range (len(self.g)):
                  ezer=[]
                  for od in range (len(self.g[0])):
                      ezer.append(self.g[od][op])
                  self.matrix.append(ezer)    
      
      
              f.close()    
      
      
      
      
          except :
              print "cannot creat a table object from this file"
              return
      
      def len(self):
          num_rows=len(self.g)
          num_cols=len(self.g[0])
          return num_rows*num_cols
      
      def get_row(self,rowname):
          for i in range (len(self.headlines)):
              if rowname==self.headrows[i]:
                  self.postionrow=i
                  return self.g[i]
      
          if not rowname in self.headrows :
              raise ValueError
      def get_column(self,colname):
          for i in range (len(self.headlines)):
              if colname==self.headlines[i]:
                  self.postioncolmn=i-1
      
                  return self.matrix[i-1]
      
          if not colname in self.headlines :
              raise ValueError
      def get_value(self,rowname,colname):
          self.get_row(rowname)
          self.get_column(colname)
          if not rowname in self.headrows :
              raise ValueError
          if not colname in self.headlines :
              raise ValueError
      
          return self.g[self.postionrow][self.postioncolmn]
      
      def get_row_name_with_max_value(self,colname):
          if not colname in self.headlines :
              raise ValueError
          max_colmn=max(self.get_column(colname))
          for i in range (len(self.matrix)):
      
              if max_colmn == self.g[i][self.postioncolmn]:
      
                  return self.headrows[i]
      

      结果应该是什么:

      >>> table = Table("table_examp1111111","\t")
          cannot create a table from this file 
      >>> table = Table("table_example1.txt","\t")             
      >>> print table.len() 
          12 
      >>> print table.get_row("Menny")
          ['M', '1', '1', '1'] 
      >>> print table.get_column("Height") 
          ['1', '2', '3'] 
      >>> print table.get_value("Sami","Age")
          3
      >>> print table.get_row_name_with_max_value("Height")
          Sami
      >>> print table.get_row_name_with_max_value("Salary")
          Sami
      

      此代码有效,但我想让它变得更加pythonic。请不要更改表单,不要添加或删除功能只修复我的syntex。 感谢。

4 个答案:

答案 0 :(得分:0)

每当你在一个对象上调用函数len()时。它将尝试调用该对象的__ len__函数。所以,如果你这样做,它可能会奏效。

def __len__(self):
    height = len(self.table)
    width = len(self.table[0])
    return height * width

答案 1 :(得分:0)

你想在__len__类上调用Table,而你看起来应该在构造函数中的table字符串数组上调用它。 您应该创建一个属性self.table,然后使用len函数,或者

def numOfCells(self): 
    return len(self.table) * len(self.table[0])

答案 2 :(得分:0)

这看起来像是使用csv模块的理想场所:

import csv

def load_csv(fname, **kwargs):
    with open(fname, 'rb') as inf:
        in_csv = csv.reader(inf, **kwargs)
        return list(in_csv)

class Table:
    def __init__(self, path, sep=','):
        self.table = load_csv(path, delimiter=sep)

        if len(self.table) == 0:
            raise ValueError('No data in file {}'.format(path))

        self.header = self.table.pop(0)
        self.cols   = len(self.header)
        self.labels = {}
        for i, row in enumerate(self.table, 1):
            # make sure rows are all same length
            if len(row) != self.cols:
                raise ValueError('row {} contains {} items - should be {}'.format(i, len(row), self.cols))
            # make sure rows-labels are unique
            lbl = row[0]
            if lbl in self.labels:
                raise ValueError('rows {} and {} - duplicate labels'.format(self.labels[lbl], i))
            else:
                self.labels[lbl] = i - 1

    @property
    def rows(self):
        return len(self.table)

    @property
    def cells(self):
        return self.rows * (self.cols - 1)  # omit row labels

    def get_row_by_label(self, lbl):
        return self.table[self.labels[lbl]]

    def get_item(self, lbl, attr):
        ndx = self.header.index(attr)
        return self.get_row_by_label(lbl)[ndx]

def main():
    t = Table('tbl.csv')
    print(t.cells)
    print(t.get_row_by_label("Menny"))
    print(t.get_item("Menny", "Age"))

if __name__=="__main__":
    main()

答案 3 :(得分:0)

修改

好的,这是您的第一个问题。根据我的理解,您需要一个能够返回表格中单元格数量的函数。此数字不包括行中人员的姓名,并且根本不包括第一行。如果我理解正确,那么这应该有效:

如果表格是:

Name,Gender,Age,Salary,Height
Menny,   M,    1,   1,   1
James,   J,    2,   2,   2
Sami,    S,    3,   3,   3

然后单元格数为'12' ......所以:

示例:

class Table:

    def __init__(self, path, sep):
        try:
            with open(path) as f:
                read_file = f.read() # will auto close the file after the read
        except:
            print "cannot create a table from this file"
            return



        self.table = read_file.split('\n') # self.table will make this easier
        self.table = [self.table[i].split(sep) for i in range(len(self.table))] # does the same as your for loop



        if len(self.table) > 0:
            for i in range(len(self.table[0])):
                if self.table[0][i] in self.table[0][0:i]:
                    raise ValueError

        row_names = []
        for i in range(1,len(self.table)):
            if len(self.table[i]) != len(self.table[0]):
                raise ValueError
            if self.table[i][0] in row_names:
                raise ValueError
            row_names.append(self.table[i][0])

       # now a function that could return the table length
   def get_num_cells(self):
       # essentially you sum each item in row[1:] for table[1:]
       return sum((sum(1 for i in range(1, len(self.table[0])))) for i in range(1,len(self.table)))

使用self.table会使这更容易,因为您不必将其包含在其他函数args中,如get_num_cells中所述,我只使用了self.table而没有将其放入函数的args。

要调用此功能,您将执行以下操作:

app = Table(path, sep)
app.get_num_cells()
# this code would be placed at the end of your file, and not inside the class

示例:

class Table()

    __init__(self, path, sep):
        etc.

   etc.etc.etc.

# now the code to create an instance of Table and call a method here like this
app = Table(path, sep) # path would be a filepath "C:/etc./file.txt", and sep = "," etc.
app.get_num_cells()

对于你的其他问题,我不完全确定你想要什么,但如果你在评论中再写一次,我会尝试。如果这对你有用,请告诉我。