如果文件已经使用Python加载到内存中,如何跳过加载?

2024-06-12 13:59:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码,试图避免在symspell.pkl文件已加载到内存中后再加载该文件:

from symspellpy import SymSpell

if 'sym_spell' in globals():
    print('sym_spell is already loaded!')
    sym_spell = global()['sym_spell']
esle:
    print('loading sym_spell...')
    sym_spell = SymSpell(max_dictionary_edit_distance=5, prefix_length=7)
    sym_spell.load_pickle('symspell.pkl')

但是python似乎总是执行else语句,即使if语句是True

以下是我的问题:

  • 有人能解释为什么Python总是在这里执行else语句吗

  • 如果文件已经在Python中加载到内存中,那么我尝试的方法是否是跳过加载文件的正确方法?如果没有,还有更好的办法吗

我正在使用python3.8.2

提前谢谢


Tags: 文件方法内存代码fromif语句else
2条回答

我正在发布我的补丁,以防它可能会有所帮助

经过多次尝试后,我使用builtins模块(而不是globals())使它工作起来 和try/except语句,如下所示:

import builtins
from symspellpy import SymSpell    

try:
    if builtins.sym_spell:
        print('sym_spell is already loaded!')
        sym_spell = builtins.sym_spell
except:
    print('sym_spell is not yet loaded! loading sym_spell...')
    sym_spell = SymSpell(max_dictionary_edit_distance=5, prefix_length=7)
    sym_spell.load_pickle('symspell.pkl')
    builtins.sym_spell = sym_spell
    

我不明白您想做什么,但是if语句总是错误的,因为globals中没有“sym_拼写”。我想你是想检查“符号拼写”而不是“符号拼写”

编辑:

Is what I tried a right way to skip loading file if it is already loaded in memory in Python? If not, is there a better way?

不,我不认为有什么方法可以满足你的要求。但是如果你的文件非常大,你不想一次又一次地加载相同的数据。那么,这对你来说是最好的解决方案。Yoi可以查看Jupyter LabJupyter Notebook
Jupyter实验室:

JupyterLab: Jupyter’s Next-Generation Notebook Interface JupyterLab is a web-based interactive development environment for Jupyter notebooks, code, and data. JupyterLab is flexible: configure and arrange the user interface to support a wide range of workflows in data science, scientific computing, and machine learning. JupyterLab is extensible and modular: write plugins that add new components and integrate with existing ones.

Jupyter笔记本:

The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.

在这里,您可以一次加载数据,而无需导入该数据,就可以多次使用。您现在可以直接从浏览器中测试它,以查看它的性能。从那里开始official website。我想这对你很有用

相关问题 更多 >