Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Counter object which is formed by processing a large set of documents.

I want to store this object in a file. And this object needs to be used in another program, for that I want to load the stored Counter object to the current program from the file intact (as a counter object).

Is there any way to accomplish this?

like image 750
Prem Jith Avatar asked Apr 03 '15 16:04

Prem Jith


People also ask

How do you update a Counter in Python?

Python updating counter We can add values to the counter by using update() method. Here, we have created an empty counter “my_count = Counter()” and updated using ” my_counter. update()” method.

How do I extract a value from a Counter in Python?

Accessing Elements in Python Counter To get the list of elements in the counter we can use the elements() method. It returns an iterator object for the values in the Counter.

What does Collections Counter return in Python?

This method returns the list of elements in the counter. Only elements with positive counts are returned.


1 Answers

You can use the pickle module to serialise arbitrary Python instances to a file, and restore them at a later time to their original state.

This includes Counter objects:

>>> 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})
like image 110
Martijn Pieters Avatar answered Oct 24 '22 10:10

Martijn Pieters