You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ImportError: 无法导入'RegexpReplacer',Python代码运行报错求助

解决ImportError: cannot import name 'RegexpReplacer'的思路

我尝试运行以下代码使用replacer工具,但仍出现错误,恳请提供解决思路。我的代码如下:

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'

哥们,你遇到的这个问题其实很好解决,核心原因就是Python找不到你要导入的RegexpReplacer类,我给你几个具体的排查和解决步骤:

  • 先确认你有对应的replacer.py文件:这个RegexpReplacer并不是NLTK库自带的类,大概率是你跟着教程学习时,教程要求你先自定义的一个工具类。你需要在和你的主脚本同一个文件夹下,创建一个名为replacer.py的文件,把下面的代码复制进去:

    import re
    
    class RegexpReplacer:
        def __init__(self):
            self.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')
            ]
            self.regexes = [(re.compile(regex), repl) for (regex, repl) in self.patterns]
    
        def replace(self, text):
            s = text
            for (regex, repl) in self.regexes:
                s = re.sub(regex, repl, s)
            return s
    
  • 检查文件名是否冲突:如果你的主脚本文件名叫replacer.py,那Python会把它当成你要导入的模块,自然找不到里面的RegexpReplacer类(除非你自己在主脚本里写了这个类)。赶紧把主脚本改成别的名字,比如text_process_demo.py就可以。

  • 排查模块路径问题:如果你的replacer.py没放在主脚本的同一目录下,那你需要把它所在的文件夹路径添加到Python的模块搜索路径里,比如在主脚本开头加上这段代码:

    import sys
    sys.path.append("/实际存放replacer.py的文件夹路径")
    

    把路径换成你实际的文件夹路径就行。

内容的提问来源于stack exchange,提问作者Black Snow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:16:51