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

LPTHW第48课:nosetest报AttributeError但输出看似正常?

解决LPTHW中Lexicon类的AttributeError问题

首先说下你遇到的AttributeError: 'str' object has no attribute ''(应该是报错信息里的方法名没显示全,实际指向scan)——这个问题核心是调用方法的姿势错了!

你把scan定义成了lexicon类的实例方法,但大概率是直接拿字符串去调用这个方法了,比如写了类似:

my_words = 'go north'
my_words.scan()  # 这里必然报错,因为字符串对象根本没有scan方法!

正确的调用方式

你得先创建lexicon类的实例,再通过实例调用scan方法:

# 先实例化类,把要处理的字符串传入构造方法
lex_instance = lexicon('go north')
# 再通过实例调用scan获取结果
result = lex_instance.scan()

顺便补全你代码里未完成的部分

你代码里的output.append(('direction', ...没写完,应该把当前遍历到的单词i补充进去,完整的判断逻辑大概是这样:

for i in thewords:
    if i in direction:
        output.append(('direction', i))
    elif i in verb:
        output.append(('verb', i))
    elif i in stop:
        output.append(('stop', i))
    elif i in noun:
        output.append(('noun', i))
    elif i.isdigit():  # 用isdigit比判断数字列表更灵活,能识别多位数
        output.append(('number', int(i)))
    else:
        output.append(('error', i))

测试代码也要同步调整

如果你用nosetest做测试,要确保测试用例里是先实例化lexicon再调用scan,比如测试代码应该类似:

from your_script import lexicon

def test_basic_scan():
    lex = lexicon('north go 123 bear')
    assert lex.scan() == [
        ('direction', 'north'),
        ('verb', 'go'),
        ('number', 123),
        ('noun', 'bear')
    ]

这样调整后,那个AttributeError应该就消失了,同时你的单词扫描功能也能正常工作啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:37:56