我有一个单词列表。我想添加一个与每个单词相关联的计数器变量。我该怎么做呢?

时间:2013-06-03 01:54:15

标签: python arrays list

我有一个单词列表,让我们说它是

['a', 'b', 'c', 'd']

我有一个文档,我已经将文本文件预处理成矩阵,它是这样的:

a,b,c,d
0,1,1,0
1,1,0,0
1,1,1,1

其中1是句子中单词的存在,0表示句子中不存在该单词。我想逐行检查那个矩阵,并增加与上面原始单词列表相关联的某种计数器,这样我就可以知道最后在句子中找到了多少个单词。

我该怎么做?我是否必须创建关联数组或二维数组?有没有办法在与我可以递增的每个单词相关联的数组中创建一个新变量?

谢谢!

5 个答案:

答案 0 :(得分:3)

您可以使用collections.Counter计算字数:

>>> from collections import Counter
>>> filedata = '''\
0,1,1,0
1,1,0,0
1,1,1,1
'''
>>> counter = Counter()
>>> for line in filedata.splitlines():
    a, b, c, d = map(int, line.split(','))
    counter['a'] += a
    counter['b'] += b
    counter['c'] += c
    counter['d'] += d


>>> counter
Counter({'b': 3, 'a': 2, 'c': 2, 'd': 1})

答案 1 :(得分:3)

你需要做的就是sum每列,因为它只是0和1!

import numpy as np
array = numpy.array((matrix))
answer = np.apply_along_axis(sum,0,array[1::])
my_dict = dict(zip(matrix[0],answer))

现在你有一个字典,其中键是单词,值是出现的总数!

答案 2 :(得分:3)

我不想对密钥进行硬编码,所以可能会这样:

import csv
from collections import Counter

with open("abcd.txt", "rb") as fp:
    reader = csv.DictReader(fp)
    c = Counter()
    for row in reader:
        c.update({k: int(v) for k,v in row.iteritems()})

产生

>>> c
Counter({'b': 3, 'a': 2, 'c': 2, 'd': 1})

答案 3 :(得分:2)

from collections import defaultdict
with open("abc") as f:
    next(f)                 # skip header
    dic = defaultdict(int) 
    for line in f:
        for x,y in zip("abcd",map(int,line.split(","))):
            dic[x] += y
    print dic

<强>输出:

defaultdict(<type 'int'>, {'a': 2, 'c': 2, 'b': 3, 'd': 1})

使用collections.Counter

from collections import Counter
with open("abc") as f:
    next(f)
    c = Counter()
    for line in f:
        c.update( dict(zip ("abcd", map(int,line.split(",")) )) )
    print c  

<强>输出:

Counter({'b': 3, 'a': 2, 'c': 2, 'd': 1})

答案 4 :(得分:2)

如果您已经有描述的矩阵,您可以这样做:

mat=[['a','b','c','d'],
     [ 0,  1,  1,  0],
     [ 1,  1,  0,  0],
     [ 1,  1,  1,  1]]

print {t[0]:sum(t[1:]) for t in zip(*mat)}

打印:

{'a': 2, 'c': 2, 'b': 3, 'd': 1}