这是我正在尝试使用用户替换器的代码,但仍然出现错误,请问任何想法?这是我的代码:

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:无法导入名称“ RegexpReplacer”

最佳答案

您得到一个ImportError: cannot import name '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()中使用不同的字符串尝试此代码时,其中一些包含不,不包含或不能包含,而某些不包含这三个单词中的任何一个,请勿,不包含和不能被不能,不能和不能替换,并且所有其他字符串都不会被其他字符串替换。

关于python - ImportError:无法导入名称“RegexpReplacer”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59408431/

10-09 05:20