在Python中创建词典和扫描器

5 投票
7 回答
10112 浏览
提问于 2025-04-17 19:10

我刚开始接触编程,感觉并没有得到很好的欢迎。我一直在通过在线教程学习Python,地址是http://learnpythonthehardway.org/book/。我努力学习到第48和第49个练习,但在这之后,教程的作者就放手让学生自己去解决问题,他说“你们自己想办法”。可是我实在搞不定。我明白我需要创建一个可能的单词表(Lexicon),并且需要扫描用户输入,看看它是否和单词表中的内容匹配,但就这些我也不知道该怎么做!从我理解的来看,我需要创建一个叫做lexicon的列表:

lexicon = [
    ('directions', 'north'),
    ('directions', 'south'),
    ('directions', 'east'),
    ('directions', 'west'),
    ('verbs', 'go'),
    ('verbs', 'stop'),
    ('verbs', 'look'),
    ('verbs', 'give'),
    ('stops', 'the'),
    ('stops', 'in'),
    ('stops', 'of'),
    ('stops', 'from'),
    ('stops', 'at')
]

这样对吗?我不知道接下来该怎么做。我知道列表中的每个项目叫做元组(tuple),但这对我来说并没有什么实际意义。我该如何将用户输入的内容放入元组中呢?你明白我的意思吗?在第49个练习中,他导入了单词表,然后在Python里打印lexicon.scan("input"),这会返回一个元组列表,比如:

from ex48 import lexicon
>>> print lexicon.scan("go north")
[('verb', 'go'), ('direction', 'north')]

那么'scan()'是一个预定义的函数,还是他在单词表模块里自己创建的函数呢?我知道如果用'split()',它会把输入的内容分成一个个单词的列表,但它是怎么把'go'分配给元组('verb', 'go')的呢?

我是不是完全搞错了?我知道我问了很多问题,但我到处搜索了好几个小时,还是搞不定这个问题。请帮帮我!我会永远感激你的!

7 个回答

2

我终于做到了!

lexicon = {
    ('directions', 'north'),
    ('directions', 'south'),
    ('directions', 'east'),
    ('directions', 'west'),
    ('verbs', 'go'),
    ('verbs', 'stop'),
    ('verbs', 'look'),
    ('verbs', 'give'),
    ('stops', 'the'),
    ('stops', 'in'),
    ('stops', 'of'),
    ('stops', 'from'),
    ('stops', 'at')
    }

def scan(sentence):

    words = sentence.lower().split()
    pairs = []

    for word in words:
        word_type = lexicon[word]
        tupes = (word, word_type) 
        pairs.append(tupes)

    return pairs
3

根据ex48的说明,你可以为每种类型的单词创建几个列表。下面是第一个测试案例的示例。返回的结果是一个包含元组的列表,所以你可以把每个给定的单词添加到这个列表里。

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

class Lexicon:
    def scan(self, sentence):
        self.sentence = sentence
        self.words = sentence.split()
        stuff = []
        for word in self.words:
            if word in direction:
                stuff.append(('direction', word))
        return stuff

lexicon = Lexicon()

他提到数字和例外情况的处理方式是不同的。

3

我建议不要用列表来制作词汇表。因为你是把单词和它们的类型对应起来,所以用字典会更合适。

这是我能给出的最大提示,虽然我不会把整个代码写出来:

lexicon = {
    'north': 'directions',
    'south': 'directions',
    'east': 'directions',
    'west': 'directions',
    'go': 'verbs',
    'stop': 'verbs',
    'look': 'verbs',
    'give': 'verbs',
    'the': 'stops',
    'in': 'stops',
    'of': 'stops',
    'from': 'stops',
    'at': 'stops'
}

def scan(sentence):
    words = sentence.lower().split()
    pairs = []

    # Iterate over `words`,
    # pull each word and its corresponding type
    # out of the `lexicon` dictionary and append the tuple
    # to the `pairs` list

    return pairs

撰写回答