在Python中创建词典和扫描仪

2024-05-27 11:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编码界的新手,还没有受到热烈的欢迎。我一直试图通过在线教程http://learnpythonthehardway.org/book/来学习python。直到练习48&49,我才勉强读完这本书。这就是他让学生们放松的地方,说“你自己想办法。”但我就是做不到。我明白我需要创建一个可能单词的词汇库,我需要扫描用户输入,看看它是否与词汇库中的任何内容匹配,但仅此而已!据我所知,我需要创建一个名为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')
]

对吗?我不知道下一步该怎么办?我知道列表中的每一项都被称为一个元组,但这对我来说并不意味着什么。如何获取原始输入并将其分配给元组?你知道我的意思吗?因此,在练习49中,他导入词典,在python内部打印lexicon.scan(“input”)并返回元组列表,例如:

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

scan()是一个预定义的函数还是他在lexicon模块中创建的函数?我知道,如果使用“split()”,它会创建一个包含输入中所有单词的列表,但是如何将“go”分配给元组(“verb”,“go”)?

我离这儿很远吗?我知道我要求很多,但我到处找了几个小时,我自己都想不出这个问题。请帮忙!我将永远爱你!


Tags: 函数fromgo编码列表scan单词词汇
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

我终于做到了!

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

根据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()

他指出,数字和异常的处理方式是不同的。

相关问题 更多 >

    热门问题