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')
The Counter type is useful for counting items. It was added in python 2.7:
import collections
counts = collections.Counter()
for line in datafile:
# remove the EOL and iterate over each character
#if you desire the counts to be case insensitive, replace line.rstrip() with line.rstrip().lower()
for c in line.rstrip():
# Missing items default to 0, so there is no special code for new characters
counts[c] += 1
To see the results:
results = [(key, value) for key, value in counts.items() if key.isalpha()]
print results
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With