Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
艰苦地学习Python,练习48_Python_Tuples - Fatal编程技术网

艰苦地学习Python,练习48

艰苦地学习Python,练习48,python,tuples,Python,Tuples,我一整天都在试图解决书中“”中的test\u errors()函数 assert_equal() 我的循环总是首先返回名词,最后返回错误元组,我不知道如何中断循环,使其重新开始,但使用正确的值继续,或者根据需要按元组的顺序对其进行排序 代码如下: class Lexicon(object): def scan(self, stringo): vocabulary = [[('direction', 'north'), ('direction', 'south'), ('directio

我一整天都在试图解决书中“”中的
test\u errors()
函数

assert_equal()

我的循环总是首先返回名词,最后返回错误元组,我不知道如何中断循环,使其重新开始,但使用正确的值继续,或者根据需要按元组的顺序对其进行排序

代码如下:

class Lexicon(object):

def scan(self, stringo):
    vocabulary = [[('direction', 'north'), ('direction', 'south'), ('direction',     'east'), ('direction', 'west')],
                    [('verb', 'go'), ('verb', 'kill'), ('verb', 'eat')],
                    [('stop', 'the'), ('stop', 'in'), ('stop', 'of')],
                    [('noun', 'bear'), ('noun', 'princess')],    # Remember numbers
                    [('error', 'ASDFADFASDF'), ('error', 'IAS')],
                    [('number', '1234'), ('number','3'), ('number', '91234')]]

    self.stringo = stringo
    got_word = ''
    value = []
    rompe = self.stringo.split() #split rompe en los espacios

    for asigna in vocabulary: 
        for encuentra in asigna:          
            if encuentra[1]  in rompe:
                value.append(encuentra)

    return value   

eLexicon = Lexicon()


from nose.tools import *
from ex48.ex48 import eLexicon 

def test_directions():
    assert_equal(eLexicon.scan("north"), [('direction', 'north')])
    result = eLexicon.scan("north south east")
    assert_equal(result, [('direction', 'north'),
                  ('direction', 'south'),
              ('direction', 'east')])

def test_verbs():
    assert_equal(eLexicon.scan("go"), [('verb', 'go')])
    result = eLexicon.scan("go kill eat")
    assert_equal(result, [('verb', 'go'),
                  ('verb', 'kill'),
                  ('verb', 'eat')])

def test_stops():
    assert_equal(eLexicon.scan("the"), [('stop', 'the')])
    result = eLexicon.scan("the in of")
    assert_equal(result, [('stop', 'the'),
                  ('stop', 'in'),
                  ('stop', 'of')])

def test_nouns():
    assert_equal(eLexicon.scan("bear"), [('noun', 'bear')])
    result = eLexicon.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(eLexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')])
    result = eLexicon.scan("bear IAS princess")
    assert_equal(result, [('noun', 'bear'),
                  ('error', 'IAS'),
                  ('noun', 'princess')])

======================================================================
FAIL: tests.ex48_tests.test_errors
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/totoro/Desktop/Python/projects/ex48/tests/ex48_tests.py", line 43, in         test_errors
    ('noun', 'princess')])
AssertionError: Lists differ: [('noun', 'bear'), ('noun', 'p... != [('noun', 'bear'),     ('error', '...

First differing element 1:
('noun', 'princess')
('error', 'IAS')

- [('noun', 'bear'), ('noun', 'princess'), ('error', 'IAS')]
+ [('noun', 'bear'), ('error', 'IAS'), ('noun', 'princess')]

----------------------------------------------------------------------
Ran 5 tests in 0.006s

非常感谢您抽出时间。

测试中的单词的输入和输出顺序相同。因此,您需要为
-循环重新排序
,以便首先迭代输入:

    value = []
    for rompe in stringo.split():
        for asigna in vocabulary:
            for encuentra in asigna:
                if encuentra[1] == rompe:
                    value.append(encuentra)
这将以正确的顺序返回
encumentra
s

注1:您不应该硬编码数字或错误

注2:通过使用一两个字典,您可以大大降低此算法的复杂性

例子:
这对我来说很好,它的代码更短。这本书是很久以前写的,谢天谢地我还有文件

def check(word):
    lexicon = {
        'direction': ['north', 'south', 'east', 'west'],
        'verb': ['go', 'kill', 'eat'],
        'stop': ['the', 'in', 'of'],
        'noun': ['bear', 'princess'],
        'error': ['ASDFADFASDF', 'IAS']
    }
word = str(word)
for key in lexicon:
    if word in lexicon[key]:
        return (key, word)
    elif word.isdigit():
        return ('number', int(word))

def scan(words):
    words = words.split()
    to_return = []
    for i in words:
        to_return.append(check(i))
    return to_return
结果显示:

......
----------------------------------------------------------------------
Ran 6 tests in 0.008s

OK

告诉我此代码是否有任何错误。请在下面发表评论:D.

我刚刚完成了这个练习,希望这能给你们中的一些人一些新的想法。 这是我的解决方案:

#Set up datastructure
direction = ["north", "east", "south", "west", "up", "right", "down", "left", "back"]
verb = ["go", "stop", "kill", "eat"]
stop = ["the", "in", "of", "from", "at", "it"]
noun = ["door", "bear", "princess", "cabinet"]
vocabulary = [(direction, 'direction'), (verb, 'verb'), (stop, 'stop'), (noun, 'noun')]

def scan(sentence):
    #searches the words in the datastructure, if not found checks if it is an integer, if not returns error.
    results = []
    words = sentence.split()

    for word in words:
        found = False
        for category in vocabulary:
            if word.lower() in category[0]:
                results.append((category[1], word))
                found = True
            else:
                pass
        if found is False and isInt_str(word) is True:
            results.append(('number', int(word)))
        elif found is False and isInt_str(word) is False:
            results.append(('error', word))
        elif found is True:
            pass
        else:
            print("I'm terribly sorry, but something you entered is neither a word nor a number.")
    return results

def isInt_str(string):
    #returns True or False if string equals an integer. (i.e. 2 = True, 2*-2 = True 2**0,5 = False)
    string = str(string).strip()
    return string=='0' or (string if string.find('..') > -1 else string.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

你的问题很不清楚。请指定从ex48引发问题的确切代码段。ex48 import eLexicon
用其他内容覆盖您的防御?基本上,我的问题是如何根据列表对元组进行排序,而不是按照字母顺序,而是按照创建列表的顺序:AssertionError:list Difference:[('Non','bear'),(‘名词’、‘公主’)(‘错误’、‘国际会计准则’!=[(‘名词’、‘熊’)、(‘错误’、‘国际会计准则’、(‘名词’、‘公主’))第一个不同元素1:(‘名词’、‘公主’)(‘错误’、‘国际会计准则’)-[(‘名词’、‘熊’、‘错误’、‘国际会计准则’、‘公主’)、(‘名词’、‘公主’)]如果我可以对元组列表进行排序,那么就不会出现错误。非常感谢您的帮助。不,它不会覆盖任何内容。它只是顺序。请检查您问题中的缩进是否与您在本地的缩进匹配。谢谢您,约翰西韦布,您的解决方案帮助我澄清了我运行的循环。您编写的代码没有附加任何内容g因为对[1]是整个元组,单词只是单词,所以它们无法匹配。再次感谢您的大力帮助。对不起,这是我在这里的第一篇帖子,我需要学会正确发布。抱歉,我错过了
词汇表
的每个元素都是另一个
列表
。我已经相应地更新了我的答案。我推荐我为了降低复杂性,或者更好,使用字典,就像我的例子中一样。非常感谢你花时间在Johnsyweb上。你写的代码非常有趣,而且充满了我以前没有见过的东西。我会彻底分析它。再次感谢你的帮助,我刚才解决了这个问题,我在帮助下解决了它我从其他用户那里得到了很多答案,甚至Zed自己也帮我调整了。干杯
......
----------------------------------------------------------------------
Ran 6 tests in 0.008s

OK
#Set up datastructure
direction = ["north", "east", "south", "west", "up", "right", "down", "left", "back"]
verb = ["go", "stop", "kill", "eat"]
stop = ["the", "in", "of", "from", "at", "it"]
noun = ["door", "bear", "princess", "cabinet"]
vocabulary = [(direction, 'direction'), (verb, 'verb'), (stop, 'stop'), (noun, 'noun')]

def scan(sentence):
    #searches the words in the datastructure, if not found checks if it is an integer, if not returns error.
    results = []
    words = sentence.split()

    for word in words:
        found = False
        for category in vocabulary:
            if word.lower() in category[0]:
                results.append((category[1], word))
                found = True
            else:
                pass
        if found is False and isInt_str(word) is True:
            results.append(('number', int(word)))
        elif found is False and isInt_str(word) is False:
            results.append(('error', word))
        elif found is True:
            pass
        else:
            print("I'm terribly sorry, but something you entered is neither a word nor a number.")
    return results

def isInt_str(string):
    #returns True or False if string equals an integer. (i.e. 2 = True, 2*-2 = True 2**0,5 = False)
    string = str(string).strip()
    return string=='0' or (string if string.find('..') > -1 else string.lstrip('-+').rstrip('0').rstrip('.')).isdigit()