We need to learn a lot about the Python next function in actual use. Related technologies must be continuously learned to better master. The following describes how to use the Python next function.
The following provides an iterator implementation and a CharBufReader class that encapsulates the buf and provides an interface for reading a byte at a time (internal implementation reads data from the buf, while buf reads data from the fill buf ). This makes the code reusable.
Iterator can be used to access Python next functions. However, the efficiency is very slow, which is not optimized previously. It takes about 90 s to use file. read (1. It can be seen that the main reason is that the function call causes the slow speed of the original program. Instead, it takes a long time to buffer and read files without writing them.
- class CharBufReader(object):
- def __init__(self, mfile, bufSize = 1000):
- self.mfile = mfile
- #self.bufSize = 64 * 1024 #64k buf size
- self.capacity = bufSize
- self.buf = '' #buf of char
- self.cur = len(self.buf)
- self.size = len(self.buf)
- def __iter__(self):
- return self
- def next(self):
- if self.cur == self.size:
- #if self.cur == len(self.buf):
- #if self.cur == self.buf.__len__():
- selfself.buf = self.mfile.read(self.capacity)
- self.size = len(self.buf)
- if self.size == 0:
- raise StopIteration
- self.cur = 0
- self.cur += 1
- return self.buf[self.cur - 1]
- class Compressor():
- def caculateFrequence(self):
- """The first time of reading the input file and caculate each
- character frequence store in self.dict
- """
- self.infile.seek(0)
- reader = compressor.CharBufReader(self.infile)
- for c in reader:
- if c in self.dict:
- self.dict[c] += 1
- else:
- self.dict[c] = 0
The above is a detailed introduction to the Python next function, and I hope you will gain some benefits.