von Mises
von Mises

Reputation: 266

Count occurrence of string with spaces using Counter

I have a large tab-delimited file. I want to count the occurrences of whatever strings are in the third column for the whole file. There could be hundreds of thousands of different strings in all. I thought Counter would be good for this and I'm very close to what I want:

from collections import Counter
import csv

with open('samfile.sam') as samFile:
    sam = csv.reader(samFile, dialect='excel-tab')
    c=Counter()
    for row in sam:
        c.update(row[2].split())

The problem is that some of the strings have spaces. And it is breaking it apart into two strings and counting those. So if this is the column I'm interested in:

foo
bar
foo bar

the counter would be 2 foo, 2 bar, but I want 1 foo, 1 bar, 1 foo bar. Any suggestions ? I don't have to use Counter I just thought it would be best but if there's a more efficient way I'd love to hear it.

Upvotes: 1

Views: 192

Answers (1)

unutbu
unutbu

Reputation: 879919

Don't split the string in the third column:

for row in sam:
    c[row[2]] += 1

Upvotes: 1

Related Questions