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

标签 python python-3.x replace

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

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/

相关文章:

python - 如何添加获取我使用 from x import * 导入的模块数组?

python - 如何修复 AttributeError : module 'numpy' has no attribute 'square'

python-3.x - Google Cloud SDK 正在尝试访问不存在的 gslib.USER_AGENT

python - 如何用模式替换字符串的一部分

javascript - 如何循环替换文本中的所有文本?

javascript - Java/JSP 中处理的 MS-WORD 特殊字符

python - INSERT 上的 SQL 语法错误

python - XGBoost 与 GridSearchCV、缩放、PCA 和 sklearn 管道中的早期停止

python - 列表中的词典

python - 模块内的类