我正在做一个简短的作业,我必须在.txt文件中读取并创建一个字典,其中的键是句子中的单词数,值是特定句子的数量长度。我已经阅读了文件并确定了每个句子的长度,但是我在编写字典方面遇到了麻烦。
我已经初始化了字典并且正在尝试使用以下代码更新它(在for循环中迭代句子):
for snt in sentences:
words = snt.split(' ')
sDict[len(words)]+=1
它在第一次迭代时给出了KeyError。我确定它与我的语法有关,但我不确定如何更新字典中的现有条目。
答案 0 :(得分:2)
def revert(): builtins.__import__ = old_imp
def apply(): builtins.__import__ = custom_import
是为此目的而发明的:
defaultdicts
如果您在作业的上下文中仅限于使用纯词典,那么您需要在递增其值之前测试该键是否存在,以防止from collections import defaultdict
sDict = defaultdict(int)
for snt in sentences:
sDict[len(snt.split())] += 1
:
KeyError
答案 1 :(得分:2)
初始化字典时,它开始为空。接下来你要做的是查找一个键,以便你可以更新它的值,但是那个键还不存在,因为字典是空的。对代码的最小更改可能是使用get
字典方法。而不是:
sDict[len(words)]+=1
使用此:
sDict[len(words)] = sDict.get(len(words), 0) + 1
get
方法查找密钥,但如果密钥不存在,则会为您提供默认值。默认默认值为None
,您可以指定其他默认值,这是第二个参数,在这种情况下为0
。
更好的解决方案可能是collections.Counter
,它处理计数事件的常见用例:
import collections
s = map(str.split, sentences)
sDict = collections.Counter(map(len, s))