我正在使用 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 much open files '' 我想我可以一次打开多个文件,加入它们,关闭它们,然后重复。另外,保持文件打开也是不好的。 谢谢!
最佳答案
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
内部抛出错误。
关于Python-使用列表理解关闭同时打开的一堆文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24212368/