1

I have a pickle file having many objects. I need to have one proper object by combining all the other objects in the file. How can I do that. I tried using many commands, but none seems to work.

objs = []

while True:
    try:
        f = open(picklename,"rb")
        objs.append(pickle.load(f))
        f.close()
    except EOFError:
        break

Like the one above as shown.

OBJECT stored image :

<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb172819198>
<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb1719ce4a8>
<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb1723caeb8>
<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb172113588>
4
  • How did you pickle these objects? That will affect how you unpickle them. Commented Apr 27, 2016 at 20:57
  • @user2357112 I pickled them using pickle.dump(nltk.NaiveBayesClassifier.train(training_set),f). Where I am using the NLTK toolkit. Commented Apr 27, 2016 at 21:03
  • No, I mean how did you pickle multiple of these objects? If your pickling code made the kind of mistake your unpickling code is making, your file likely only has one classifier pickled in it. Commented Apr 27, 2016 at 21:04
  • @user2357112 I appended the objects in the same file using open(filename,"ab"). Commented Apr 27, 2016 at 21:09

1 Answer 1

1

You should use .extend() to append all items in the list to objs:

(Assuming pickle.load(f) returns a list of objects)

objs.extend(pickle.load(f))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You sir for your answer. Sir I am storing objects in my pickle, which are NaiveBayesClassifier object provided in nltk, so when I run using the above code I get TypeError: 'NaiveBayesClassifier' object is not iterable
What does pickle.load(f) return exactly? It returns a single NaiveBayesClassifier object or a list of NaiveBayesClassifier objects?
Sir I edited the answer showing the result of printing pickle.load(f)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.