计算 csv 文件中特定字符串的出现次数
Counting the occurence of a specific string in a csv file
您好,我有一个文件,我需要在其中计算单词 'Methadone' 和 'Co-Codamol' 出现的次数。它似乎打印“0”,而事实上在这个特定文件中美沙酮和辅可达莫出现的总次数是 9 次。文件如下所示:
http://i.stack.imgur.com/hUdJt.png
这是我的代码:
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
读取文件并计算字符串出现的次数:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
print(content.count("Methadone"))
只要您的文件不是太大,这就可以了。
不确定您要在什么上下文中尝试执行此操作,但如果您可以使用 grep,那将非常简单:
grep -o 字符串文件 | wc -l
假设'Methadone'和'Co-Codamol'是两种不同的药物,我建议您将最后一行替换为:
print 'Number of prescriptions is %s' % (number['Methadone'] + number['Co-Codamol'])
您好,我有一个文件,我需要在其中计算单词 'Methadone' 和 'Co-Codamol' 出现的次数。它似乎打印“0”,而事实上在这个特定文件中美沙酮和辅可达莫出现的总次数是 9 次。文件如下所示:
http://i.stack.imgur.com/hUdJt.png
这是我的代码:
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
读取文件并计算字符串出现的次数:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
print(content.count("Methadone"))
只要您的文件不是太大,这就可以了。
不确定您要在什么上下文中尝试执行此操作,但如果您可以使用 grep,那将非常简单:
grep -o 字符串文件 | wc -l
假设'Methadone'和'Co-Codamol'是两种不同的药物,我建议您将最后一行替换为:
print 'Number of prescriptions is %s' % (number['Methadone'] + number['Co-Codamol'])