Python列表理解太慢
我有231个pdf文件,希望将它们转换为字符串格式。随后,我将把这些字符串保存到一个txt文件中 我能够为此创建一个代码(当我为较少的元素运行代码时,我检查了它是否有效),但是python甚至在10小时后也没有完成程序的执行 我使用“for循环”尝试了相同的代码,但是速度太慢了。你知道我怎样才能让代码更快吗 这是我的密码:Python列表理解太慢,python,python-3.x,performance,for-loop,list-comprehension,Python,Python 3.x,Performance,For Loop,List Comprehension,我有231个pdf文件,希望将它们转换为字符串格式。随后,我将把这些字符串保存到一个txt文件中 我能够为此创建一个代码(当我为较少的元素运行代码时,我检查了它是否有效),但是python甚至在10小时后也没有完成程序的执行 我使用“for循环”尝试了相同的代码,但是速度太慢了。你知道我怎样才能让代码更快吗 这是我的密码: from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter#process_pdf from
from pdfminer.pdfinterp import PDFResourceManager,
PDFPageInterpreter#process_pdf
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
def pdf_to_text(pdfname):
# PDFMiner boilerplate
rsrcmgr = PDFResourceManager()
sio = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, sio, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Extract text
fp = open(pdfname, 'rb')
for page in PDFPage.get_pages(fp):
interpreter.process_page(page)
fp.close()
# Get text from StringIO
text = sio.getvalue()
# Cleanup
device.close()
sio.close()
return text
lista2 = [pdf_to_text(k) for k in lista1]
其中lista1
是包含我的231个PDF的列表
pdf文件是从中提取的。我只选择了名称中带有“Livro”一词的文件。这是生成器的一个重要用例:保存内存 通常,您所需要做的就是迭代文件,一次转换一个文件,然后将输出流传输到其他地方。比如说:
for f in files:
text = pdf_to_text(f)
output.write(text)
--那么你就不想(或不需要)一个列表理解,事实上你根本不需要创建一个列表。相反,只需一次迭代元素一次即可。或者创建一个生成器,如果这更有意义的话
请记住,如果仍有对内存的引用,则垃圾收集器无法释放内存。如果您创建了一个列表,那么其中的所有元素(以及这些元素引用的项目)都必须同时保存在内存中。通常,只有在计划频繁或以非线性顺序访问元素时,才需要此选项
你也应该考虑处理大文件的可能性,即使你能做<代码>分配<代码> > />代码>转换< /代码> /代码> DealPosie<代码>,如果我们谈论许多值得读/写的千兆字节,可能仍然“太慢”。在这种情况下,最好的选择通常是考虑使用C扩展来更好地控制内存的分配和使用。另外,
pypy
在绝大多数情况下都能工作,通常比CPython快得多。看起来您正在处理的文件相当大(10MB),因此预计执行时间较长。除了更加并行化和更加谨慎地使用内存之外,要加快程序的执行速度,您所能做的并不多。也就是说,您可以执行以下操作:
- 将多线程与多处理池一起使用
- 将每个文本文件分别写入磁盘以释放内存
#!/usr/bin/env python
import os
from multiprocessing import Pool, cpu_count
from io import BytesIO
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
PDF_DIRECTORY = "pdfs"
def pdf_to_text(pdf_filename):
# PDFMiner boilerplate
pdf_resource_manager = PDFResourceManager()
bytes_io = BytesIO()
device = TextConverter(
pdf_resource_manager, bytes_io, codec="utf-8", laparams=LAParams())
interpreter = PDFPageInterpreter(pdf_resource_manager, device)
# Extract text
with open(pdf_filename, "rb") as fp:
for page in PDFPage.get_pages(fp):
interpreter.process_page(page)
text = str(bytes_io.getvalue())
# Cleanup
bytes_io.close()
device.close()
# Print current filename with some of the parsed text
print("{} - {}".format(pdf_filename, text[:15].replace("\n", "")))
return text
def process_pdf_file(pdf_filename):
text_filename = "{}.txt".format(os.path.splitext(pdf_filename)[0])
# Write the text file to disk to avoid having to keep
# it in memory
with open(text_filename, "w") as text_file:
text_file.write(pdf_to_text(pdf_filename))
def main():
pdf_filename_list = []
for filename in os.listdir(PDF_DIRECTORY):
if not filename.endswith(".pdf"):
continue
pdf_filename_list.append(os.path.join(PDF_DIRECTORY, filename))
MULTITHREAD = True
if MULTITHREAD:
# Use a thread pool to process multiple PDF files at the same time
pool = Pool(cpu_count())
pool.map(process_pdf_file, pdf_filename_list)
else:
# Version without thread pool
for pdf_filename in pdf_filename_list:
process_pdf_file(pdf_filename)
main()
你能用PDF文件发布一个zip存档文件以便我们复制吗?分析器输出在哪里?据我所知-你可以将
PDFMiner样板文件
从函数移到\uuu main\uuuu
范围,并在处理完所有PDF文件后进行清理。我不认为循环或理解占用了大部分时间。你可能想让你的函数不那么沉默,并记录你的进度,看看发生了什么。我打开了一些随机的“Livro”文件。179页。看来你记性不好了