title: Converting plural to singular in a text file with Python
body: <p>I have txt files that look like this:</p>
  
  <pre><code>word, 23
  Words, 2
  test, 1
  tests, 4
  </code></pre>
  
  <p>And I want them to look like this:</p>
  
  <pre><code>word, 23
  word, 2
  test, 1
  test, 4
  </code></pre>
  
  <p>I want to be able to take a txt file in Python and convert plural words to singular. Here's my code:</p>
  
  <pre><code>import nltk
  
  f = raw_input("Please enter a filename: ")
  
  def openfile(f):
      with open(f,'r') as a:
         a = a.read()
         a = a.lower()
         return a
  
  def stem(a):
      p = nltk.PorterStemmer()
      [p.stem(word) for word in a]
      return a
  
  def returnfile(f, a):
      with open(f,'w') as d:
          d = d.write(a)
      #d.close()
  
  print openfile(f)
  print stem(openfile(f))
  print returnfile(f, stem(openfile(f)))
  </code></pre>
  
  <p>I have also tried these 2 definitions instead of the <code>stem</code> definition:</p>
  
  <pre><code>def singular(a):
      for line in a:
          line = line[0]
          line = str(line)
          stemmer = nltk.PorterStemmer()
          line = stemmer.stem(line)
          return line
  
  def stem(a):
      for word in a:
          for suffix in ['s']:
              if word.endswith(suffix):
                  return word[:-len(suffix)]
              return word
  </code></pre>
  
  <p>Afterwards I'd like to take duplicate words (e.g. <code>test</code> and <code>test</code>) and merge them by adding up the numbers next to them. For example:</p>
  
  <pre><code>word, 25
  test, 5
  </code></pre>
  
  <p>I'm not sure how to do that. A solution would be nice but not necessary.</p>