gpt4 book ai didi

python - 导入错误: cannot import name 'RegexpReplacer'

转载 作者:行者123 更新时间:2023-12-01 00:14:42 24 4
gpt4 key购买 nike

这是我的代码,我正在尝试使用替换程序,但仍然收到错误,请问有什么想法吗?这是我的代码:

import nltk
from replacer import RegexpReplacer
import sys

replacer = RegexpReplacer()
replacer.replace("Don't hesitate to ask questions")
print(replacer.replace("She must've gone to the market but she didn't go"))

这是我的错误:

ImportError: cannot import name 'RegexpReplacer'

最佳答案

您收到ImportError:无法导入名称“RegexpReplacer”,因为替换程序中没有名为 RegexpReplacer 的模块。相反,使用以下代码创建一个名为 RegexpReplacer 的类:

import re

replacement_patterns = [
(r'don\'t', 'do not'),
(r'didn\'t', 'did not'),
(r'can\'t', 'cannot')
]

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()
replacer.replace("Don't hesitate to ask questions.")
print(replacer.replace("She must've gone to the market but she didn't go."))

输出:

She must've gone to the market but she did not go.

当您在 replacer.replace() 中尝试使用不同的字符串时,其中一些包含 don't、did't 或 can't,而另一些则不包含任何这三个词 don'tdidn'tcan't 将被 do not 替换, 没有不能,并且所有其他字符串都不会替换为不同的字符串。

关于python - 导入错误: cannot import name 'RegexpReplacer' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408431/

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