有没有办法让python为for循环的每次迭代都打印到文件,而不是将所有内容都存储在缓冲区中?

乘风 nlp 493

原文标题Is there a way to make python print to file for every iteration of a for loop instead of storing all in the buffer?

我正在遍历一个非常大的文档以尝试对其进行归类。不幸的是,python 似乎并没有为每一行打印到文件,而是在打印之前遍历了整个文档,因为我的文件的大小超过了内存……在我之前将我的文档分成更小的块我想知道是否有一种方法可以强制 python 为每一行打印到文件。

到目前为止,我的代码如下:

import spacy
nlp = spacy.load('de_core_news_lg')
  
fin = "input.txt" 
fout = "output.txt"
    
    
#%%
    
with open(fin) as f:
   corpus = f.readlines()
    
corpus_lemma = []
    
for word in corpus:
   result = ' '.join([token.lemma_ for token in nlp(word)])
   corpus_lemma.append(result)
    
   with open(fout, 'w') as g:
      for item in corpus_lemma:
         g.write(f'{item}')

为了给代码加分,这里有人建议:Ho to do lemmatization on German text?

原文链接:https://stackoverflow.com//questions/71661340/is-there-a-way-to-make-python-print-to-file-for-every-iteration-of-a-for-loop-in

回复

我来回复
  • Victor Maricato的头像
    Victor Maricato 评论

    如中所述:如何逐行读取大文件?

    如果您在with块内进行词形还原,Python 将使用缓冲 I/O 逐行处理读取。

    在您的情况下,它看起来像:

    import spacy
    nlp = spacy.load('de_core_news_lg')
    
    fin = "input.txt" 
    fout = "output.txt"
    
    
    #%%
    
    corpus_lemma = []
    
    with open(fin) as f:
        for line in f:
            result = " ".join(token.lemma_ for token in nlp(line))
            corpus_lemma.append(result)
    
    with open(fout) as g:
        for item in corpus_lemma:
            g.write(f"{item}")
    
    
    2年前 0条评论