APD
APD

Reputation: 169

Replacing words matching regular expressions in python

import re
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
(r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
(r'(\w+)\'d', '\g<1> would')
 ]
class RegexpReplacer(object):

   def __init__(self, patterns=replacement_patterns):
      self.patterns = [(re.compile(regex), repl) for (regex, repl)          
                      in pattern]
   def replace(self, text):
      s = text
      for (pattern, repl) in self.patterns:
          (s, count) = re.subn(pattern, repl, s)
   return s


 rep=RegexpReplacer()
 print rep.replace("can't is a contradicton")

I have copied this code from Python Text Processing with NLTK 2.0 Cookbook by Jacob Perkins

However my expected output is: cannot is a contradiction

Actual Output is: can't is a contradiction

I'm unable to pinpoint the error in t

Upvotes: 0

Views: 940

Answers (2)

rchang
rchang

Reputation: 5246

Your code has some indentation issues and typos - I'm not quite sure how the interpreter was giving you any output at all. After I fixed those, I got your expected output.

import re
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
(r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
(r'(\w+)\'d', '\g<1> would')
 ]
class RegexpReplacer(object):

   def __init__(self, patterns=replacement_patterns):

      # Fixed this line - "patterns", not "pattern"
      self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]

   def replace(self, text):
      s = text
      for (pattern, repl) in self.patterns:
          (s, count) = re.subn(pattern, repl, s)

      # Fixed indentation here
      return s


rep=RegexpReplacer()
print rep.replace("can't is a contradicton")

Upvotes: 2

Aran-Fey
Aran-Fey

Reputation: 43306

Either use raw strings or escape the quotation marks, but not both.

>>> print r'won\'t'
won\'t
>>> print 'won\'t'
won't

or, if you prefer raw strings:

>>> print r"won't"
won't

Upvotes: 0

Related Questions