【问题标题】:AttributeError: 'RegexpReplacer' object has no attribute 'replace'AttributeError:“RegexpReplacer”对象没有属性“replace”
【发布时间】:2019-09-12 13:01:11
【问题描述】:

在定义类(RegexpReplacer)时,我发现属性错误,我没有得到解决这个问题的方法。代码如下,还有错误:

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"))

我发现了错误

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

请大家帮忙

【问题讨论】:

    标签: python python-3.x attributeerror


    【解决方案1】:

    replace方法被埋在__init__里面,你要纠正缩进:

    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"))
    

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2019-08-02
      • 2016-04-21
      • 2018-05-10
      • 2019-05-07
      相关资源
      最近更新 更多