使用Python 3.8.1
新程序员,如果行话有点不对,请原谅我。我目前正在从一本书中进行学习练习,目的是接受用户输入并返回一个与用户输入匹配的词性的元组(例如,“ go”将返回(“ verb”,“ go”)) )。我建立了一个起作用的if-then结构,但是我想知道是否可以在使用它的同时使用字典来实现相同的目的,因此添加新类别会更简单(而不是添加在if-then中设置一个树,然后我就可以创建一个字典条目。
部分想法是,如果用户输入的内容不在一组关键字中,我想返回一个错误,那么使用dict.get()之类的内容并不是我想要的,因为我不想要返回的空值。
编辑:为澄清起见,我正在寻找一种方法,可以向函数提供字符串,并让该函数返回字典的键值,而该字符串位于键的关联集中。更详细地说,如果我有这本字典:
lexicon = {
'direction': {'east','south','north','west'}
}
我希望能够做这样的事情:
lexicon.???('south') == 'direction'
哪里???是我不知道它是否存在的功能。
这是我目前拥有的:
directions = {'north','south','east','west'}
verbs = {'go','kill','eat'}
stops = {'the','in','of'}
nouns = {'bear','princess'}
def scan(input_string):
words = input_string.split()
result = []
for word in words:
if word in directions:
result.append(('direction', word))
elif word in verbs:
result.append(('verb', word))
elif word in stops:
result.append(('stop', word))
elif word in nouns:
result.append(('noun', word))
else:
try:
word = int(word)
result.append(('number',word))
except:
result.append(('error',word))
return result
答案 0 :(得分:0)
您可以使用断言来检查用户是否写了这些关键字或其他内容。这是一个有用的链接:https://wiki.python.org/moin/UsingAssertionsEffectively
答案 1 :(得分:0)
如果键不在dict中,则可以使用dict.get()的第二个参数返回响应。设置为False可以减少决策树:
data_dict = {'directions': [], 'verbs': [], ...}
if word in data_dict.get('direction', False):
result.append(('direction', word))
与外部对象结合使用以迭代字典中的键(使用data_dict.keys()),以便您可以进一步减少它!
答案 2 :(得分:0)
是的,实际上这很简单,但对于新的编码器来说可能并不直观。首先确定类别和相关单词的字典,然后在跟踪类别标签的同时简单地查找每个单词。
categories = {
'direction': {'north', 'south', 'east', 'west'},
'verb': {'go', 'kill', 'eat'},
'conjunction': {'the', 'in', 'of'},
'noun': {'bear', 'princess'},
}
...
for category, wordset in categories.items():
if word in wordset:
result.append((category, word))
顺便说一句,您可以通过将分类放入函数中来简化scan
,并且可以改善其他一些方面:
def categorize(word):
for category, wordset in categories.items():
if word in wordset:
return (category, word)
try:
word = int(word) # Keep the try-block slim
except ValueError: # Bare "except" is bad practice
return ('error', word)
else:
return ('number', word)
def scan(phrase):
# Use a list comprehension instead of a bunch of appending
return [categorize(word) for word in phrase.split()]
print(scan('go north princess'))
# -> [('verb', 'go'), ('direction', 'north'), ('noun', 'princess')]
print(scan('5 steps'))
# -> [('number', '5'), ('error', 'steps')]
答案 3 :(得分:0)
在术语上加上类别
directions = {'north','south','east','west'}
verbs = {'go','kill','eat'}
stops = {'the','in','of'}
nouns = {'bear','princess'}
ctgs = (
'directions',
'verbs',
'stops',
'nouns'
)
vals = (
directions,
verbs,
stops,
nouns
)
d = {v: c for c, vc in zip(ctgs, vals) for v in vc}
def scan(input_string):
words = input_string.split()
result = []
for word in words:
ctg = d.get(word)
if ctg is not None:
result.append((ctg, word))
else:
try:
word = int(word)
result.append(('number',word))
except ValueError:
result.append(('error',word))
return result
s = 'go west 3 jump'
print(scan(s))
产生
[('verbs', 'go'), ('directions', 'west'), ('number', 3), ('error', 'jump')]