如何将collections.Counter对象写入python中的文件,然后从文件中重新加载并将其用作计数器对象

Pre*_*ith 6 python collections python-2.7

我有一个Counter通过处理大量文档形成的对象.

我想将此对象存储在一个文件中.此对象需要在另一个程序中使用,因为我想将存储的Counter对象从文件中完整地加载到当前程序(作为计数器对象).

有没有办法实现这个目标?

Mar*_*ers 9

您可以使用该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(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})
Run Code Online (Sandbox Code Playgroud)