1

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.

2
  • 2
    Don't use row[2].split()....? Commented Sep 5, 2013 at 17:54
  • If I dont use .split it counts individual letters which is much much worse Commented Sep 5, 2013 at 17:57

1 Answer 1

1

Don't split the string in the third column:

for row in sam:
    c[row[2]] += 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.