Açıklama Yok

readsample.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import os
  2. import sys
  3. class readsample:
  4. def __init__(self, file, hash_keys=None, delimeter=None, skip=2):
  5. "Open file and read the header."
  6. self.fd = open(file, "r")
  7. self.delimeter = delimeter
  8. self.hash_keys = hash_keys
  9. self.read_head(skip)
  10. pass
  11. def next(self):
  12. "Read one record of the file and hash the fields"
  13. line = self.fd.readline()
  14. if not line:
  15. return None
  16. if self.delimeter != None:
  17. result = line.split(delimeter)
  18. else:
  19. result = line.split()
  20. if self.hash_keys:
  21. return self.createHash(result, self.hash_keys)
  22. else:
  23. return [float(x) for x in result]
  24. def readAll(self):
  25. "Read all records and return a list"
  26. sample_list = []
  27. sample = self.next()
  28. while sample:
  29. sample_list.append(sample)
  30. sample = self.next()
  31. return sample_list
  32. def read_head(self, skip = 2):
  33. "This is to remove the header of the file"
  34. "Reusing this code requires modifying this function"
  35. "Most times just skip lines, and just change the default skip number"
  36. for i in range(skip):
  37. self.fd.readline()
  38. def createHash(self, s_line, hash_keys):
  39. "This is to create a hash with the fields of the record"
  40. "The record is already splitted in one list"
  41. hash_res = {}
  42. for i in range(len(hash_keys)):
  43. hash_res[hash_keys[i]] = float(s_line[i]) # want to improve this to tuples
  44. return hash_res
  45. def close(self):
  46. self.fd.close()
  47. def main():
  48. "Main to test the library"
  49. samples = readsample(sys.argv[1], ["peak", "intensity"])
  50. value = samples.next()
  51. while value:
  52. print value
  53. value = samples.next()
  54. samples.close()
  55. samples = readsample(sys.argv[2], None, None, 0)
  56. print samples.readAll()
  57. if __name__ == '__main__':
  58. main()