Reputation: 395
Hi I have a file in which I need to count how many times the word 'Methadone' and 'Co-Codamol' appear. It seems to print '0' when in fact in this particular file the total times methadone and co-codamol occur is 9 times. Here is what the file looks like:
https://i.sstatic.net/hUdJt.png
and here is my code:
import csv
import collections
number = collections.Counter()
with open('C:\Users\Desktop\practice jan.csv') as input_file:
for row in csv.reader(input_file, delimiter=','):
number[row[1]] += 1
print 'Number of prescriptions is %s' % number['Methadone' + 'Co-Codamol']
>> Number of opioid prescriptions is 0
Upvotes: 1
Views: 3423
Reputation: 876
Assuming that 'Methadone' and 'Co-Codamol' are two different drugs, I suggest you to replace your last line with:
print 'Number of prescriptions is %s' % (number['Methadone'] + number['Co-Codamol'])
Upvotes: 0
Reputation: 230
Not sure what context you're trying to do this in, but if you can use grep it's very simple:
grep -o string file | wc -l
Upvotes: 0
Reputation: 602
Read the file and count the number of occurences of your string:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
print(content.count("Methadone"))
As long as your file is not too large, this will do the work.
Upvotes: 1