计算csv fi中特定字符串的出现次数

2024-10-02 08:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一个文件,我需要数一数“美沙酮”和“辅酶多胺”这两个词出现的次数。它似乎打印“0”,而实际上在这个特定的文件中,美沙酮和co-codamol发生的总次数是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

Tags: 文件ofcsvimportnumberinputis次数
3条回答

假设“美沙酮”和“辅酶异戊醇”是两种不同的药物,我建议您将最后一行替换为:

print 'Number of prescriptions is %s' % (number['Methadone'] + number['Co-Codamol'])

读取文件并计算字符串出现的次数:

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()
    print(content.count("Methadone"))

只要你的文件不是太大,这将做的工作。在

不确定您要在什么环境下执行此操作,但如果您可以使用grep,则非常简单:

grep-o字符串文件| wc-l

相关问题 更多 >

    热门问题