Ann*_*ise 0 python dictionary if-statement count try-except
我想计算部分语音标签.到目前为止,我有一个存储在字典中的词性标记(用于德语),其中POS标记所在的键,以及出现次数的值.
当我统计时,我想将'NN'和'NE'概括为一个变量'nouns_in_text',因为它们都是名词.我成功地完成了这个.当我有一个输入文本,其中我有'NN'和'NE',在这种情况下我的代码正在工作,我得到正确的结果,意味着'NN'和'NE'的总和.
但问题是,当我有一个输入文本,例如只有'NN'而没有'NE'时,我得到一个KeyError.
我需要代码来查看输入文本中是否存在"NN"或"NE".如果有'NN'和'NE',那么总结它们.如果只有'NN',那么只返回'NN'的出现次数,如果只有'NE'则返回相同的值.如果既没有'NN'也没有'NE'返回0或"无".
我想要一个代码,它可以在以下描述的场景中适用于所有三个,而不会出现错误.
# First Scenario: NN and NE are in the Input-Text
myInput = {'NN': 3, 'NE': 1, 'ART': 1, 'KON': 1}
# Second Scenario: Only NN is in the Input-Text
#myInput = {'NN': 3, 'ART': 1, 'KON': 1}
# Third Scenario: Neither NN nor NE are in the Input-Text
#myInput = {'ART': 1, 'KON': 1}
def check_pos_tag(document):
return document['NN'] + document['NE']
nouns_in_text = check_pos_tag(myInput)
print(nouns_in_text)
# Output = If NN and NE are in the input text I get 4 as result
# But, if NN or NE are not in the input text I get a KeyError
Run Code Online (Sandbox Code Playgroud)
我想我可以或者应该用if-else条件或try-except块来解决这个问题.但我不确定如何实现这个想法...有什么建议吗?非常感谢你提前!:-)
如果不存在则使用dict.get带有参数的用户将被返回.(key, default)keydocumentdefault
def check_pos_tag(document):
return document.get('NN', 0) + document.get('NE', 0)
Run Code Online (Sandbox Code Playgroud)