我知道已经有很多人问这个问题是这样的,但我真的找不到适合我的解决方案。
在ex48中。我写了“lexicon.py”并测试它。但它报告错误:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "D:\pyhomework\ex48\skeleton\tests\lexicon_tests.py", line 31, in test_errors
assert_equal(Lexicon.scan("ASDFASDF"),[('errors','ASDFASDF')])
AttributeError:'module'对象没有属性'scan'
这是lexicon.py:
class Lexicon(object):
def __init__(self):
self.dic = {'direction':('north','south','east'),
'verb':('go','kill','eat'),
'stop':('the','in','of'),
'noun':('bear','princess'),
'number':('1234','3','91234'),
'error':('ASDFASDF','IAS')}
def scan(self,words):
self.word = words.split()
self.result = []
for item in self.word:
for key,value in self.dic.items():
if item in value:
self.result.append((key,item))
return self.result
这是lexicon_tests.py
from nose.tools import *
from ex48 import Lexicon
def test_direction():
assert_equal(Lexicon.scan("north"),[('direction','north')])
result = Lexicon.scan("north south east")
assert_equal(result,[('direction','north'),('direction','south'),('direction','east')])
def test_verbs():
assert_equal(Lexicon.scan("go"),[('verb','go')])
result = Lexicon.scan("go kill eat")
assert_equal(result,[('verb','go'),('verb','kill'),('verb','eat')])
def test_stops():
assert_equal(Lexicon.scan("the"),[('stop','the')])
result = Lexicon.scan("the in of")
assert_equal(result,[('stop','the'),('stop','in'),('stop','of')])
def test_nouns():
assert_equal(Lexicon.scan("bear"),[('noun','bear')])
result = Lexicon.scan("bear princess")
assert_equal(result,[('noun','bear'),('noun','princess')])
def test_numbers():
assert_equal(Lexicon.scan("1234"),[('number','1234')])
result = Lexicon.scan("3 91234")
assert_equal(result,[('number','3'),('number','91234')])
def test_errors():
assert_equal(Lexicon.scan("ASDFASDF"),[('errors','ASDFASDF')])
result = Lexicon.scan("bear IAS princess")
assert_equal(result,[('noun','bear')('error','IAS')('noun','princess')])
这是骨架:
-bin
-docs
-ex48 (-__init__.py -Lexicon.py)
-tests (-__init__.py -lexicon_tests.py)
-setup
我尝试了几种方法,但仍然遇到同样的错误。 谢谢你的任何建议。
答案 0 :(得分:0)
当您编写from ex48 import Lexicon
时,导入的内容是Lexicon.py文件作为python模块。但是,此模块包含一个Lexicon类,其中包含您要使用的方法。
要解决您的错误,请尝试以下导入语句:from ex48.lexicon import Lexicon
这样您将使用lexicon.py文件中定义的Lexicon
对象。
答案 1 :(得分:0)
from ex48 import Lexicon
因此您导入了模块 lexicon.py
。
在模块 lexicon.py
中,您有一个类 Lexicon
。
所以要调用类Lexicon
的方法,你必须使用符号
Lexicon.Lexicon.method()