4

as defining the class(RegexpReplacer) i found the attribute error and i didn't get the solution for this problem. the code is given bellow and also the error:

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 patterns]
        def replace(self, text):
                         s = text
                         for (pattern, repl) in self.patterns:
                             s = re.sub(pattern, repl, s)
                             return s
replacer=RegexpReplacer()
print(replacer.replace("can't is a contradicton"))

i found the error

Traceback (most recent call last):
 print(replacer.replace("can't is a contradicton"))
AttributeError: 'RegexpReplacer' object has no attribute 'replace'

please if anyone can help

1 Answer 1

2

The replace method is buried inside the __init__, you have to correct the indentation:

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 patterns]
    def replace(self, text):
         s = text
         for (pattern, repl) in self.patterns:
             s = re.sub(pattern, repl, s)
         return s
replacer=RegexpReplacer()
print(replacer.replace("can't is a contradicton"))
Sign up to request clarification or add additional context in comments.

Comments

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.