(Nosetest) AssertionError: None != inlearningpythonthehardway ex48 lexicon scan

(Nosetest) AssertionError: None != inlearningpythonthehardway ex48 lexicon scan

请参阅 LearningPythonTheHardWay exercise48 以了解有关这些代码用途的更多详细信息。我还是新手,我知道还有很多需要改进的地方或更好的方法。

我在这里遇到的主要问题是鼻子测试的结果,代码附在下面lexicon.py之后。

简而言之,我有 1 个错误和 5 个失败。

错误:

NameError: global name 'ASDFADFASDF' is not defined

失败:

AssertionError: None != [('direction', 'north')]
AssertionError: None != [('verb', 'go')]
AssertionError: None != [('stop', 'the')]
AssertionError: None != [('noun', 'bear')]
AssertionError: None != [('number', 1234)]

结果是 None 而不是右侧的答案。对于错误,我的代码得到了类似的结果,除了与 test_error 相比,我有

[('error', 'ASDFADFASDF')]

测试结果是

[('error', ASDFADFASDF)]

至于失败,我收到的典型失败消息是:

 File "C:\xxx\xxxxxx\learningpython\projectex48\skeleton\tests\lexicon_tests.py", line 13, in test_verb
    assert_equal(lexicon.scan("go"),[('verb', 'go')])
AssertionError: None != [('verb', 'go')]
-------------------- >> begin captured stdout << ---------------------
[('verb', 'go')]

--------------------- >> end captured stdout << ----------------------

我不知道为什么 1 个元素只有 运行,例如 "go kill eat" python 只有 运行s "go"。我仍在尝试找出逻辑以及如何解决它。任何人都可以帮助我确定为什么我没有通过 5 次测试并有 1 个错误的问题。

我花了几周的时间为这个练习编写我自己的扫描函数版本,这是 lexicon.py:

的代码
direction = [('direction', 'north'),
        ('direction', 'south'),
        ('direction', 'east'),
        ('direction', 'west'),
        ('direction', 'up'),
        ('direction', 'down'),
        ('direction', 'left'),
        ('direction', 'right'),
        ('direction', 'back')
]

verbs = [('verb', 'go'),
        ('verb', 'stop'),
        ('verb', 'kill'),
        ('verb', 'eat')
]

stop_words = [('stop', 'the'),
            ('stop', 'in'),
            ('stop', 'of'),
            ('stop', 'from'),
            ('stop', 'at'),
            ('stop', 'it')
]

nouns = [('noun', 'door'),
        ('noun', 'bear'),
        ('noun', 'princess'),
        ('noun', 'cabinet')
]


library = tuple(nouns + stop_words + verbs + direction)


def convert_number(x):
    try:
        return int(x)
    except ValueError:
        return None

def scan(input):
    element = input.split()
    data = library
    i = 0
    z = 0
    output = []
    temp = True
    while (i == 0) or (not (element[(i-1)] == element[-1])):
        try:
            j = 0
            while (j == 0) or (not data[(j-1)][1] == data [-1][1]):
                matching = data[j][1]
                if (matching == element[i]):
                    output.append(data[j])
                    j += 1
                    z += 1
                    temp = False

                else:
                    while (data[j][1] == data [-1][1]) and (temp == True):
                        convert = convert_number(element[i])
                        a = tuple(['number', convert])
                        b = tuple(['error', element[i]])

                        if convert == a[1] and not(convert == None):    
                            output.append(a)
                            temp = False

                        else:
                            output.append(b)
                            temp = False
                        j += 1
            i += 1
            temp = True
        except ValueError:
            return None
    else:
        pass
    print output

上面是我用来测试的简化版本,概念是搜索和gather/add输入对应的数据并保存并附加到输出中作为元组,最后打印它们一起出去。

下面是我直接从书上抄来的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_verb():
    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("ASDFADFASDF"), [('error', ASDFADFASDF)]) #refer to Update#1
    result = lexicon.scan("bear IAS princess")
    assert_equal(result, [('noun', 'bear'),
                        ('error', 'IAS'),
                        ('noun', 'princess')])

这是我保存文件的地方:

$ mkdir projectsex48
$ cd projectsex48/
$ mkdir skeleton
$ cd skeleton
$ mkdir bin
$ mkdir ex48   #(lexicon.py)
$ mkdir tests  #(lexicon_tests.py)
$ mkdir doc

**更新 #1:**针对错误

NameError: global name 'ASDFADFASDF' is not defined

这是因为 ASDFADFASDF 的 lexicon_tests.py 中缺少括号 '',如下所示:

    assert_equal(lexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')])

现在我有 6 个函数 returns None.

失败
AssertionError: None != [('direction', 'north')]
AssertionError: None != [('verb', 'go')]
AssertionError: None != [('stop', 'the')]
AssertionError: None != [('noun', 'bear')]
AssertionError: None != [('number', 1234)]
AssertionError: None != [('error', 'ASDFADFASDF')]

是的!!我终于解决了。

我错了,用

结束了扫描功能
print output

我更正了

return output

所以最终修正后的代码是:

direction = [('direction', 'north'),
        ('direction', 'south'),
        ('direction', 'east'),
        ('direction', 'west'),
        ('direction', 'down'),
        ('direction', 'left'),
        ('direction', 'right'),
        ('direction', 'back')
]

verbs = [('verb', 'go'),
        ('verb', 'stop'),
        ('verb', 'kill'),
        ('verb', 'eat')
]

stop_words = [('stop', 'the'),
            ('stop', 'in'),
            ('stop', 'of'),
            ('stop', 'from'),
            ('stop', 'at'),
            ('stop', 'it')
]

nouns = [('noun', 'door'),
        ('noun', 'bear'),
        ('noun', 'princess'),
        ('noun', 'cabinet')
]


library = tuple(nouns + stop_words + verbs + direction)


def convert_number(x):
    try:
        return int(x)
    except ValueError:
        return None


def scan(input):
    #include uppercase input for searching. (Study Drills no.3)
    lowercase = input.lower()
    #element is what i want to search.
    element = lowercase.split()
    #orielement is the original input which have uppercase, for 'error' type
    orielement = input.split()
    #library is tuple of the word types from above. You can replace with your data source.
    data = library
    #i is used to evaluate the position of element
    i = 0
    #z is used to indicate the position of output, which is the data that match what i search, equals to "i".
    z = 0
    #create a place to store my output.
    output = []
    #temp is just a on/off switch. Turn off the switch when i get any match for that particular input.
    temp = True
    #creating a condition which evaluates the total search needed to be done and follows the sequence by +1.
    while not(i == len(element)):
        try:
            #j is used to position the word in the library, eg 'door', 'bear', 'go', etc which exclude the word type.
            j = 0
            while not (j == len(data)):
                #data[j][1] all the single word in library
                matching = data[j][1]
                #when the word match, it will save the match into the output.
                if (matching == element[i]):
                    output.append(data[j])
                    #print output[z]
                    j += 1
                    z += 1
                    #to switch off the search for else: below and go to next input search. Otherwise they would be considerd 'error'
                    temp = False
                    #else is everything that is not in the library.
                else:
                    while (data[j][1] == data [-1][1]) and (temp == True):
                        #refer to convert_number, to test if the input is a number, here i use orielement which includes uppercase
                        convert = convert_number(orielement[i])
                        #a is used to save number only.
                        a = tuple(['number', convert])
                        #b is to save everything
                        b = tuple(['error', orielement[i]])
                        #conver is number a[1] is the access the number inside, if it returns None from number then it wont append. 
                        if convert == a[1] and not(convert == None):    
                            output.append(a)
                            temp = False
                        else:
                            output.append(b)
                            #keep the switch off to escape the while loop!
                            temp = False
                    #searching in next data
                    j += 1
                #next word of input
                i += 1
                temp = True
    except ValueError:
                return output
else:
    pass
return output

输出是我用来存储搜索结果的元组。