簡體   English   中英

如何將collections.Counter對象寫入python中的文件,然后從文件中重新加載並將其用作計數器對象

[英]how to write the collections.Counter object to a file in python and then reload it from the file and use it as a counter object

我有一個Counter對象,它是通過處理大量文檔而形成的。

我想將此對象存儲在文件中。 並且這個對象需要在另一個程序中使用,為此我想將存儲的Counter對象從文件完整地加載到當前程序(作為一個計數器對象)。

有什么辦法可以做到這一點嗎?

您可以使用pickle模塊將任意 Python 實例序列化為文件,並在稍后將它們恢復到原始狀態。

這包括Counter對象:

>>> import pickle
>>> from collections import Counter
>>> counts = Counter('the quick brown fox jumps over the lazy dog')
>>> with open('/tmp/demo.pickle', 'wb') as outputfile:
...     pickle.dump(counts, outputfile)
... 
>>> del counts
>>> with open('/tmp/demo.pickle', 'rb') as inputfile:
...     print(pickle.load(inputfile))
... 
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 't': 2, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM