#!/usr/bin/env python3

tm = open('./timemachine.txt', 'r')
Dict = {}

for line in tm:
    line = line.strip()
    line = line.translate('!"#$%&\'()*+-./:;<=>?@[\\]^_`{|}~')
    line = line.lower()
    List = line.split(' ')

    for word in List:
        if word in Dict:
            count = Dict[word]
            count += 1
            Dict[word] = count
        else:
            Dict[word] = 1

for word, count in Dict.iteritems():
    print(word + ":" + str(count))

In the program above I'm getting the error -> builtins.AttributeError: 'dict' object has no attribute 'iteritems'
I'm following code that was given to me by the magazine Guru Guide / Coding Academy
Any ideas? Thanks.

It's a little old way of doing this,but it work if fixing as Girb posted.
You should not make a seperate line for count.
Do it like this.

my_dict = {}
s = 'hello world hello'
for word in s.split():
    if word in my_dict:
        my_dict[word] += 1
    else:
        my_dict[word] = 1

print(my_dict) #{'world': 1, 'hello': 2}

The next step in improving this,can be to use get() method.

my_dict = {}
s = 'hello world hello'
for word in s.split():
    my_dict[word] = my_dict.get(word, 0) + 1

print(my_dict) #{'world': 1, 'hello': 2}

Your code with full Python power,here i use colletions.Counter.
And regex to remove punctuation.
You should also look at PEP-8,e.g not use capitale letter in variable name.

from collections import Counter
import re    

with open('count_test.txt') as f:
    text = f.read().lower()
words = re.findall(r'\w+', text)

print(Counter(words))
print(Counter(words).most_common(2))

Edited 1 Year Ago by snippsat

Comments
love the get()

Thanks. As far as using a capital letter for a variable name I was only doing that because I noticed that my IDE was lighting up the variable names dict and list, I knew my code was written prior to python3 and I was thinging that python3 may had added some built ins named dict and list and could be causing me problems, so it was a last minute quick fix tryout. Thanks again.

This question has already been answered. Start a new discussion instead.