Having trouble with counter for a dictionary from a txt file

Viewed 21

For my assignment, we're supposed to pull email addresses from a txt file and insert them into a dictionary in the main program file, then have a counter to show the frequency of how many times the email address has sent an email. So far I've successfully pulled the emails from the txt file, but I'm having trouble setting up the counter within the dictionary. With the code I have I keep getting these errors:

Traceback (most recent call last):
  File "", line 23, in <module>
    main()
  File "", line 15, in main
    frequency[item] += 1
TypeError: can only concatenate str (not "int") to str
def main():
    frequency = {'email':[]}
    cvs_colums=['email','count']
    outputcvs = 'outputcvs.cvs'
    with open('files/input.txt','r') as reader:
        for line in reader:
            if line.startswith('From:'):
                line = line.rstrip('\n')
                email = line[6:]
                frequency['email']= email
                for item in frequency:
                    if (item in frequency):
                        frequency[item] += 1
                    else:
                        frequency[item] = 1

if __name__ == '__main__':
   main()
1 Answers

I think in your dictionary you are assigning the email address as both key and value so when you try to +1 you can't add 1 to an email address. This is the error you are getting.

frequency['email']= email

I think set value as 1 unless key already exists.

def main():
    frequency = {}
    cvs_colums=['email','count']
    outputcvs = 'outputcvs.cvs'
    with open('files/input.txt','r') as reader:
        for line in reader:
            if line.startswith('From:'):
                line = line.rstrip('\n')
                email = line[6:]
                if email in frequency.keys():
                    frequency[email] += 1
                else:
                    frequency[email]= 1
        
 if __name__ == '__main__':
    main()
Related