gpt4 book ai didi

python - "Open-ended"字典键? (LPTHW 练习 48 相关)

转载 作者:行者123 更新时间:2023-11-28 22:51:15 24 4
gpt4 key购买 nike

我正在做 Learn Python The Hard Way 的练习 48 并编写 lexicon 字典和 scan 模块来运行以下测试:

from nose.tools import *
from ex47 import lexicon


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

除了数字和错误测试之外,我已经弄清楚了大部分内容。当用户输入的是字典中未定义的单词时,需要用 error 值名称标记,如果是数字 - number 值名称。显然,我可以抢先将所有将要测试的输入添加到字典中,但那是作弊。

我的字典是这样的:

lexicon = {
'north': 'direction',
'princess': 'noun',
# etc...
}

有没有办法将数字和未定义单词的“开放式”定义融入其中?

更新。这是一个可行的解决方案:

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

for word in words:
try:
number = int(word)
tupes = ('number', number)
pairs.append(tupes)

except ValueError:
try:
word_type = lexicon[word]
tupes = (word_type, word)
pairs.append(tupes)
except KeyError:
tupes = ('error', word)
pairs.append(tupes)
return pairs

最佳答案

您可以使用带有可选默认参数的字典的 get 方法:

d = {"a":'letter', 4:'number'}
result = d.get("not in d", 'error')
print result
# error

在 python 中使用 try/except 循环来检查关键错误也很常见,尽管在这种情况下它可能有点矫枉过正。

d = {"a":'letter', 4:'number'}
try:
result = d['not in d']
except KeyError:
result = 'error'
print result
# error

我认为在 Python 中检查字符串是否为数字的最简单方法是在 try except block 中使用 float 或 int,就像上面的第二个示例一样。您使用哪一个取决于您是否要将“1.2”和“3.4e5”视为数字。

关于python - "Open-ended"字典键? (LPTHW 练习 48 相关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21685901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com