如何将 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
module 将任意 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})
我有一个 Counter
对象,它是通过处理大量文档形成的。
我想将这个对象存储在一个文件中。并且这个对象需要在另一个程序中使用,为此我想将存储的 Counter
对象从文件原封不动地加载到当前程序(作为计数器对象)。
有什么办法可以做到吗?
您可以使用 pickle
module 将任意 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})