Once upon a time a time this upon a
输出:
dictionary {
'Once upon': 1,
'upon a': 2,
'a time': 2,
'time a': 1,
'time this': 1,
'this upon': 1
}
CODE:
def countTuples(path):
dic = dict()
with codecs.open(path, 'r', 'utf-8') as f:
for line in f:
s = line.split()
for i in range (0, len(s)-1):
dic[str(s[i]) + ' ' + str(s[i+1])] += 1
return dic
我收到此错误:
File "C:/Users/user/Anaconda3/hw2.py", line 100, in countTuples
dic[str(s[i]) + ' ' + str(s[i+1])] += 1
TypeError: list indices must be integers or slices, not str
如果我删除+=
和公正的地方=1
一切正常就好了,我想这个问题是,当我尝试访问的条目提取没有按”值现在还存在吗?
我能做些什么来解决这个问题?要求你的代码的最小变化
使用“计数器”... –
计数器将对文件上的每个元组进行迭代。我承受不起,时间复杂度将是n^2,我想避免这种情况。 @WillemVanOnsem –
如果您使用'zip',则不需要... –