I’m having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains.
So far I have this, which I can run through CDM, and state a file to open. I’ve messed around with regular expressions, still can’t figure out how to count individual characters. Any ideas? sorry if I explained this badly.
import sys
import re
filename = raw_input()
count = 0
datafile=open(filename, 'r')
I’d stay away from regexes. They’ll be slow and ugly. Instead, read the entire file into a string, and use the built-in string method
countto count the characters.To put it together for you:
Then, you have a dictionary
countscontaining all the counts. For example,counts['a']gives you the number ofas in the file. Or, for the entire list of counts, docounts.items().