title: Reading and writing POS tagged sentences from text files using NLTK and Python
body: <p>Does anyone know if there is an existing module or easy method for reading and writing part-of-speech tagged sentences to and from text files?  I'm using python and the Natural Language Toolkit (NLTK).  For example, this code:</p>
  
  <pre><code>import nltk
  
  sentences = "Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world."
  
  tagged = nltk.sent_tokenize(sentences.strip())
  tagged = [nltk.word_tokenize(sent) for sent in tagged]
  tagged = [nltk.pos_tag(sent) for sent in tagged]
  
  print tagged
  </code></pre>
  
  <p>Returns this nested list:</p>
  
  <pre><code>[[('Call', 'NNP'), ('me', 'PRP'), ('Ishmael', 'NNP'), ('.', '.')], [('Some', 'DT'), ('years', 'NNS'), ('ago', 'RB'), ('-', ':'), ('never', 'RB'), ('mind', 'VBP'), ('how', 'WRB'), ('long', 'JJ'), ('precisely', 'RB'), ('-', ':'), ('having', 'VBG'), ('little', 'RB'), ('or', 'CC'), ('no', 'DT'), ('money', 'NN'), ('in', 'IN'), ('my', 'PRP$'), ('purse', 'NN'), (',', ','), ('and', 'CC'), ('nothing', 'NN'), ('particular', 'JJ'), ('to', 'TO'), ('interest', 'NN'), ('me', 'PRP'), ('on', 'IN'), ('shore', 'NN'), (',', ','), ('I', 'PRP'), ('thought', 'VBD'), ('I', 'PRP'), ('would', 'MD'), ('sail', 'VB'), ('about', 'IN'), ('a', 'DT'), ('little', 'RB'), ('and', 'CC'), ('see', 'VB'), ('the', 'DT'), ('watery', 'NN'), ('part', 'NN'), ('of', 'IN'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]]
  </code></pre>
  
  <p>I know I could easily dump this into a pickle, but I really want to export this as a segment of a larger text file.  I'd like to be able to export the list to a text file, and then return to it later, parse it, and recover the original list structure.   Are there any built in functions in the NLTK for doing this?  I've looked but can't find any...</p>
  
  <p>Example output:</p>
  
  <pre><code>&lt;headline&gt;Article headline&lt;/headline&gt;
  &lt;body&gt;Call me Ishmael...&lt;/body&gt;
  &lt;pos_tags&gt;[[('Call', 'NNP'), ('me', 'PRP'), ('Ishmael', 'NNP')...&lt;/pos_tags&gt;
  </code></pre>