python有意思的yield

yield主要使用在遍历、迭代等会占用较大内存的地方。

yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator。调用这个generator function的时候,返回的是一个 iterable 对象!在 for 循环执行时,每次循环都会执行generator函数内部的代码,并返回一个yield出来的东西,下次迭代时会从上一轮yield中断的地方继续执行,一直到结束。

举例(1)要按行处理一个本地文件,首先要读取本地文件,以往的做法是读到一个list中,也就是读到了内存中,但当文件太大时,这个做法是不可取的。下面通过创建一个本地语料库的类,其中__iter__()函数对文件中的每一行进行迭代。

class MyCorpus(object):
    def __init__(self, dir_path):
        self.dir_path = dir_path

    def __iter__(self):
        for line in open(self.dir_path, 'r',  encoding = 'utf-8'):
            yield line.split()
 
 

下面产生一个generator实例,就可以在for语句中调用了。(Gensim中调用语料库就是这样操作的)

corpus_word2vec_memory_friendly = MyCorpus(spoa_segmentedOrgs_output_path)

for corpus_row in corpus_word2vec_memory_friendly:
    print(corpus_row )

举例(2)上面通过类的定义实现generator,直接用函数也是可以的。

def raw_text_generator(file_name):
    
    for line in open(file_name, 'r', encoding = 'utf-8'):
            
        yield line
下面在for语句中调用

for line in raw_text_generator(text_file_name):
    
    print(line)




参考:

https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/

猜你喜欢

转载自blog.csdn.net/dongweionly/article/details/79887017
今日推荐