我一直在使用架子以这种方式存储大量物品:
以字符串为键、列表为值的字典:
即
data["MITL"] = ["Radio And Television Broadcasting And Communications Equipment", "Communication Equipment"]
或更简洁地说:
...
SIXH.L Machine Tools & Accessories,
GOPAIST.BO Steel & Iron,
HERITGFOO.NS Food Wholesale,
MITL Radio And Television Broadcasting And Communications Equipment, Communication Equipment,
MMLP Oil Refining, Marketing, Oil & Gas Pipelines,
SESL.PA Diversified Electronics,
...
<≈ 30,000 entries>
我从此 .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>
据我所知,该文件写得很好,它正在检索我的问题数据。
来自文档:“如果使用数据库,数据库也会(不幸地)受到 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
我见过其他人遇到导致相同错误的问题,但他们使用的是 7.4.1 之前的 Python 版本,我认为他们的错误是由不同的原因造成的。 那么,我的问题是:
dbm 有哪些限制?
有没有办法解决搁置中大型对象(包含大型列表作为值的字典)的问题?
如果不是,如果我不想将数据保存在 RAM 中,有什么更好的方法来存储数据? (我想这就是使用Shelve的目的)