2

我正在使用 gensim 开发 LDA 模型。为此,我基本上是打开文本文件,构建字典,然后运行模型。

要打开我使用的文件:

files = [codecs.open(infile, 'r', 'utf-16', 'ignore') for infile in sample_list] 

其中 sample_list 是文件路径列表。我需要使用 codecs.open 因为文本使用不同的语言(而且我还没有更新 Python)。

我的问题是我不知道如何在使用它们后关闭所有文件。有任何想法吗?我已经尝试了几件事。我不能在这里使用常规循环,因为我的以下步骤是:

texts = [" ".join(file.readlines()[0:]) for file in files]

当我使用超过 5,000 个文件时,我收到错误 '' IOError: [Errno 24] Too many open files '' 我想我可以一次打开多个文件,加入它们,关闭它们,然后重复。此外,保持文件打开也很糟糕。谢谢!

4

1 回答 1

4
def read_contents(filename):
    with codecs.open(filename, 'r', 'utf-16', 'ignore') as infile:
        return ' '.join(infile)

texts = [read_contents(filename) for filename in sample_list]

使用with相当于做:

def read_contents(filename):
    try:
        infile = codecs.open(filename, 'r', 'utf-16', 'ignore')
        return ' '.join(infile)
    finally:
        infile.close()

finally关键字确保close()无论如何都会执行,即使脚本在try.

于 2014-06-13T19:14:45.033 回答