【问题标题】:count occurencies of a word计算一个单词的出现次数
【发布时间】:2014-03-09 18:17:34
【问题描述】:

我查了类似的主题,但结果很差。

我有一个这样的文件:

S1_22   45317082    31  0   9   22  1543
S1_23   3859606 40  3   3   34  2111
S1_24   48088383    49  6   1   42  2400
S1_25   43387855    39  1   7   31  2425
S1_26   39016907    39  2   7   30  1977
S1_27   57612149    23  0   0   23  1843
S1_28   42505824    23  1   1   21  1092
S1_29   54856684    18  0   2   16  1018
S1_29   54856684    18  0   2   16  1018
S1_29   54856684    18  0   2   16  1018
S1_29   54856684    18  0   2   16  1018

我想计算第一列中单词的出现次数,并在此基础上编写输出文件,其中包含说明 uniq if count == 1 和 multi if count > 0 的附加字段

我生成了代码:

import csv
import collections

infile = 'Results'

names = collections.Counter()

with open(infile) as input_file:
    for row in csv.reader(input_file, delimiter='\t'):
        names[row[0]] += 1
    print names[row[0]],row[0]

但它不能正常工作

由于文件太大,我无法将所有内容都放入列表中

【问题讨论】:

    标签: python count


    【解决方案1】:

    如果您希望此代码正常工作,您应该缩进您的 print 语句:

        names[row[0]] += 1
        print names[row[0]],row[0]
    

    但你真正想要的是:

    import csv
    import collections
    
    infile = 'Result'
    
    names = collections.Counter()
    
    with open(infile) as input_file:
        for row in csv.reader(input_file, delimiter='\t'):
            names[row[0]] += 1
    
    for name, count in names.iteritems():
        print name, count
    

    编辑:要显示该行的其余部分,您可以使用第二个字典,如下所示:

    names = collections.Counter()
    rows = {}
    
    with open(infile) as input_file:
        for row in csv.reader(input_file, delimiter='\t'):
            rows[row[0]] = row
            names[row[0]] += 1
    
    for name, count in names.iteritems():
        print rows[name], count
    

    【讨论】:

      【解决方案2】:

      最后的打印语句看起来不像你想要的。由于它的缩进,它只执行一次。它将打印 S1_29,因为这是循环最后一次迭代中 row[0] 的值。

      你在正确的轨道上。而不是那个打印语句,只需遍历计数器的键和值并检查每个值是否大于或等于 1。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2021-04-19
        相关资源
        最近更新 更多