gpt4 book ai didi

python - AttributeError: 'RegexpReplacer' 对象没有属性 'replace'

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:44 25 4
gpt4 key购买 nike

在定义类(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 - AttributeError: 'RegexpReplacer' 对象没有属性 'replace',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55809581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com