python - AttributeError:“RegexpReplacer”对象没有属性“replace”
问题描述
在定义类(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'
请如果有人可以帮助
解决方案
该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"))
推荐阅读
- python - 比较python中的两个csv文件并跳过给定的行号
- java - Spring Boot:使用外键执行@query
- python - 有没有办法重新加载整个 Plotly Dash py 脚本?
- postman - Postman 请求 PUT 与 body --> form-data 与图像 req.file 未定义为什么?
- database - 具有单个 varchar 列与多个 varchar 列的复合索引
- php - mysqli_stmt::fetch(); 返回一个布尔值,但应该返回一个数组
- angular - ionic 3 angularx - flatpickr 弹出月历的所有日子都被禁用
- angular - Angular:ngx bootstrap 模式的单元测试用例覆盖率
- python - GridSearchCV 不适用于 Pipeline 的内存参数和并发性 (n_jobs > 1)
- cypress - 我们如何获取令牌并在响应中显示它