簡體   English   中英

如何在不運行 for 循環的情況下使 class 的 iter 方法返回一個值?

[英]How to make iter method of a class return a value without running the for loop?

我有一個 class,它有一個__iter__方法,如下所示

class Mycorpus:
    
    '''This class helps us to train the model without loading the whole dataset to the RAM.'''
    
    def __init__(self, filepath= text_file):
        self.filepath = filepath
        
    def __iter__(self):
        with open(self.filepath,'r') as rfile:
            csv_reader = csv.DictReader(rfile, delimiter=',')
            for row in csv_reader:
        
                # splitter splits the conversation into client and agent part
                client_convo, agent_convo = convo_split.splitter(row['Combined'])

                client_tokens = preprocess(client_convo)
                agent_tokens = preprocess(agent_convo)
                
                yield client_tokens

我將此 object 傳遞給 function ,這需要此 object 在迭代時一次返回一組令牌。 即, client_tokensagent_tokens 我希望__iter__產生一個client_tokens ,並在下一次迭代中產生來自同一客戶端代理對的agent_tokens 我不想同時產生兩組令牌,因為它會破壞功能。 一次只有一個。 我的主要目標是避免循環兩次文件並在相同的對話中再次使用拆分器 function。

我試過做類似下面的事情。

def __init__(self, filepath= text_file):
        self.filepath = filepath
        self.agent_turn = 0

def __iter__(self):
        with open(self.filepath,'r') as rfile:
            csv_reader = csv.DictReader(rfile, delimiter=',')
 
            if self.agent_turn:
                self.agent_turn = 0
                yield agent_tokens
            
            else:
                for row in csv_reader:
                
                    # splitter splits the conversation into client and agent part
                    client_convo, agent_convo = convo_split.splitter(row['Combined'])

                    client_tokens = preprocess(client_convo)
                    agent_tokens = preprocess(agent_convo)
                    self.agent_turn = 1
                    yield client_tokens

但是上面的代碼只給出了client_tokens 在不使用 memory 的整個數據集的情況下,有沒有更好的方法? 我的要求甚至可以使用__iter__方法嗎? 非常感謝任何幫助或指導。

正如許多示例向您展示的那樣,您使用了兩個 yield 語句。 請記住,生成器/迭代器在yield語句之后重新進入,而不是在 function 的頂部。

        for row in csv_reader:
    
            # splitter splits the conversation into client and agent part
            client_convo, agent_convo = convo_split.splitter(row['Combined'])

            client_tokens = preprocess(client_convo)
            agent_tokens = preprocess(agent_convo)
            
            yield client_tokens
            yield agent_tokens

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM