Python Count Number Of Occurence


 
Thread Tools Search this Thread
Top Forums Programming Python Count Number Of Occurence
# 1  
Old 07-23-2015
Python Count Number Of Occurence

Hello,

I have a programming assignment to count number of occurrences of hours in particular file. Below is the code:

Code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
largest = None
fh = open(fname)

counts = dict()

test = list()
for line in fh:
    line = line.rstrip()
    if not line.startswith('From'): continue
    if line.startswith('From:'): continue
    words = line.split()
    h = words[5]
    h = h.split(':')
    test.append(h[0])    
    for w in tes:
     counts[w] = counts.get(w, 0 ) + 1
print test
print counts

Output of "print test" which I believe is ok:

Code:
['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10', '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16']

Output of "print counts":

Code:
{'11': 111, '10': 42, '15': 47, '14': 22, '04': 24, '16': 31, '19': 6, '18': 26, '09': 39, '17': 9, '06': 10, '07': 11}

I don't know why "print counts" is giving a large number of counts?

---------- Post updated at 11:52 AM ---------- Previous update was at 09:53 AM ----------

I figured out the issue!

It was the nested FOR loop:

for w in tes: counts[w] = counts.get(w, 0 ) + 1
I have written the code again:

Code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
largest = None
fh = open(fname)

counts = dict()

test = list()
lst = list()
for line in fh:
    line = line.rstrip()
    if not line.startswith('From'): continue
    if line.startswith('From:'): continue
    words = line.split()
    h = words[5]
    h = h.split(':')
    test.append(h[0])
for w in test:
 counts[w] = counts.get(w, 0 ) + 1
print test
print counts

Thanks!
# 2  
Old 07-24-2015
A few things to consider, if you care about it.

Code:
if len(fname) < 1 : fname = "mbox-short.txt"

More Pythonic
Code:
if not fname:
    fname = "mbox-short.txt"

Code:
fh = open(fname)

You are not checking that the operation to open the fname was possible, also if it was possible, you should close it afterward.

Code:
line = line.rstrip()

No necessary since it does not interfere with what you are extracting.

Code:
    for w in tes:
     counts[w] = counts.get(w, 0 ) + 1

Indentation of counts[w] is not consistent with the rest of the code (it is less)
Code:
    if not line.startswith('From'): continue
    if line.startswith('From:'): continue

continue should be in the next line, indented. Furthermore, it is not necessary, since the only lines you want is From without the `:'

Here's is a rendition with those details changed.
Code:
fname = raw_input("Enter file name: ")
if not fname:
    fname = "mbox-short.txt"

# it checks that the file is open successfully and
# it will automatically close it when done.
with open(fname) as fh:
    counts = {}
    test = []
    for line in fh:
        if line.startswith('From '):
            h = line.split()[5].split(':')[0]
            test.append(h)
            if h not in counts:
                counts[h] = 1
            else:
                counts[h] += 1
print test
print counts

# 3  
Old 10-27-2015
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Print occurence number

Hi folks, I have a file with lots of lines in a text file,i need to print the occurence number after sorting based on the first column as shown below, thanks in advance. sam,dallas,20174 sam,houston,20175 sam,atlanta,20176 jack,raleigh,457865 jack,dc,7845 john,sacramento,4567 ... (4 Replies)
Discussion started by: tech_frk
4 Replies

2. UNIX for Dummies Questions & Answers

Add number of occurence

Good morning, I need help to add number of occurence based on column 1 & column 5 file input 81161267334|1|100000|81329998077|20150902 81161267334|1|50000|82236060161|20150902 81161268637|1|25000|81329012229|20150911 81161269307|1|25000|81327019134|20150901... (3 Replies)
Discussion started by: radius
3 Replies

3. Shell Programming and Scripting

[perl script] print the assembly instruction and count the occurence

Hi, I have a input file(text file) with the following lines. 0x000000 0x5a80 0x0060 BRA.l 0x60 ;file:UserCall.s ;function:_user_call_table ;C_sourceLine:24 0x000002 0x1bc5 RETI ;file:UserCall.s ;function:_user_call_table ;C_sourceLine:30 0x000003 0x6840 MOV R0L,R0L ;file:UserCall.s... (6 Replies)
Discussion started by: acdc
6 Replies

4. Shell Programming and Scripting

Count number of character occurence but not from quotation marks

I have the following string: 31-01-2012, 09:42:37;OK;94727132638;"Mozilla/5.0 (Linux; U; Android 2.2.1)";3G;WAP;I need a script which is counting the occurrence of semicolons ( ; ) but exclude the ones from the quotation marks. In the string given as example there are 8 semicolons but the script... (3 Replies)
Discussion started by: calinlicj
3 Replies

5. Shell Programming and Scripting

Number each occurence using sed

hi, I need to number each occurrence of a pattern within a file using sed. Given object 0000 object 111 object 222 I need following 1.object 0000 2.object 111 3.object 222 (5 Replies)
Discussion started by: xerox
5 Replies

6. UNIX for Dummies Questions & Answers

How to count the occurence of a character in a line

Suppose i have data like :- 1,2,3,4,5 a,b,c x,y,z,t I want to count the occurence of , (comma) in every line. Waiting for a solution. (5 Replies)
Discussion started by: sumit207
5 Replies

7. UNIX for Advanced & Expert Users

How to count the occurence of a character in a line

Suppose i have data like :- 1,2,3,4,5 a,b,c x,y,z,t I want to count the occurence of , (comma) in every line. Waiting for a solution.:) (1 Reply)
Discussion started by: sumit207
1 Replies

8. UNIX for Dummies Questions & Answers

grep the number of first occurence

File1.txt ....... ....... OMC LA OMC LK OMC LS ........ ........ Above is the content of File1.txt, i want to get the Number of Occurence to order, lets say if OMC LA = 1, OMC LS=3, and OMC LK=2.. omc_ident="OMC LA" or "OMC LK" or "OMC LS" omc_num=`grep '^OMC' File1.txt| grep... (4 Replies)
Discussion started by: neruppu
4 Replies

9. UNIX for Dummies Questions & Answers

search& count for the occurence of a word

Greetings, I need to search and count all the occurences of a word in all the files in a directory. Any suggestions greatly appreciated. Thanks (1 Reply)
Discussion started by: skoppana
1 Replies

10. Shell Programming and Scripting

Count the number of occurence of perticular word from file

I want to count the number of occurence of perticular word from one text file. Please tell me "less" command is work in ksh or not. If it is not working then instead of that which command will work. :confused: (40 Replies)
Discussion started by: rinku
40 Replies
Login or Register to Ask a Question