Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regular expressions and CMD

Tags:

python

regex

cmd

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')
like image 218
Unknown Avatar asked Feb 21 '23 01:02

Unknown


1 Answers

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
like image 61
Kevin Coffey Avatar answered Feb 28 '23 22:02

Kevin Coffey