python中对象的搁置库限制

2024-09-30 22:16:46 发布

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

我一直用shelve以这种方式存储大量的对象:

以字符串为键、列表为值的字典:

data["MITL"] = ["Radio And Television Broadcasting And Communications Equipment", "Communication Equipment"]

或者更简洁地说:

^{pr2}$

我从这个.db文件中提取并导出到另一个.db文件中,因此行业是关键,列表由股票符号组成。在

...
Industrial Electrical Equipment ['PLPC', 'MAG', 'LPTH', 'IIN', 'CUI', 'ULBI', 'APWC', 'CAPC', 'SVT', 'ARTX', 'CPST', 'OSIS', 'LGL', 'BW', 'HPJ', 'AOS', 'FLUX', 'AMSC', 'GTI', 'RTBC', 'AUSI', 'AETI', 'AIMC', 'HYGS', 'BLDP', 'HOLI', 'NPWZ', 'LIME', 'ESNC', 'ZBB', 'CSTU', 'AXPW', 'GBLL', 'EMR', 'BDC', 'BNSO', 'ENS', 'REFR', 'ABAT', 'FELE', 'CYLU', 'XIDEQ', 'LYTS', 'GAI', 'AMOT', 'CUI.V', 'LSCG']
Toy & Hobby Stores ['BBW']
Distribution ['MNST', 'FMX', 'STZ', 'FIZZ', 'BREW', 'THST', 'LBIX', 'ROX', 'COKE', 'KOF', 'PEP', 'COT', 'REED', 'SAM', 'MGPI', 'DPS', 'CCE', 'BORN', 'KO', 'BUD', 'CCU', 'WVVIP', 'TAP', 'WVVI', 'DEO', 'ABEV', 'VCO']
Home Health Care ['AFAM', 'SCAI', 'ADUS', 'AMED', 'LHCG', 'BIOS', 'CHE', 'HASC']
...
<≈ 300 entries>

据我所知,这个文件写得很好,检索数据是我的问题。在

From the documentation:“如果使用数据库管理,数据库也(不幸地)受到dbm的限制-这意味着存储在数据库中的对象(pickle表示)应该相当小,并且在极少数情况下,键冲突可能导致数据库拒绝更新。”

但是我找不到任何关于dbm限制的信息,即使是文档。原因一定是因为我作为值存储的列表太大了。在

以下是代码摘录:

industriesAndTheirStocks = shelve.open("industriesAndTheirStocks")
print(len(industriesAndTheirStocks)) # just to make a point at how many keys there are, proving it's the size of the lists stored that contains the issue

for industry in industriesAndTheirStocks: # fails here because 'industriesAndTheirStocks' can't be iterated through, because it sent a negative number as the size to __iter__
    print("{:<15}".format(industry), end="")
    print(industriesAndTheirStocks[industry])

以及错误/输出:

374
Traceback (most recent call last):
  File "read_from_shelve_stock_industry_file.py", line 144, in <module>
    if __name__ == "__main__":main()
  File "read_from_shelve_stock_industry_file.py", line 128, in main
    display_shelve_contents_by_industry()
  File "read_from_shelve_stock_industry_file.py", line 42, in display_shelve_contents_by_industry
    for industry in industriesAndTheirStocks:
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/shelve.py", line 95, in __iter__
    for k in self.dict.keys():
SystemError: Negative size passed to PyBytes_FromStringAndSize

Process finished with exit code 1

我见过其他人也有同样的问题,但他们使用的是Python 7.4.1之前的版本,我认为他们的错误是另一个原因。 Python shelve module question

那么,我的问题是:

dbm的局限性是什么?在

有没有一种方法可以修复在shelve中有大对象(包含大列表作为值的字典)?在

如果没有,如果我不想把数据保存在RAM中,有什么更好的方法来存储数据呢?(我想这就是使用Shelve的目的)


Tags: 文件the数据对象inpy数据库列表