Input:
Once upon a time a time this upon a
Conclusion:
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
I get this error:
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
If you delete +=and just put =1everything will work fine, I think the problem is that I'm trying to access the record in order to extract a value that does not exist yet?
What can I do to fix this?
source
share