计算原始文件中的词频并映射它们

2024-10-01 00:26:28 发布

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

我正在尝试使用一个修正版的计数矢量器,我用它来适应一个系列。 然后我得到单元格中所有值的计数之和。 这是我正在安装计数矢量器的系列

["dog cat mouse", " cat mouse", "mouse mouse cat"]

最终结果应该类似于:

[1+3+4, 3+4, 4+4+3]

我已经尝试过使用Counter,但在这种情况下它实际上不起作用。 到目前为止,我只成功地得到了一个稀疏矩阵,但它打印出了单元格中元素的总数。但是,我想将计数映射到整个系列


Tags: 元素矢量counter情况矩阵cat计数dog
2条回答

计数器列表的项目只能以字符串的形式存储,之后可以使用eval()对字符串进行求值

代码:

lst = ["dog cat mouse", " cat mouse", "mouse mouse cat"]
res = {}
res2 = []
for i in lst:
    for j in i.split(' '):
        if j not in res.keys():
            res[j] = 1
        else:
            res[j] += 1

for i in lst:
    res2.append('+'.join([str(res[j]) for j in i.split(' ')]))

print(res2)

结果(res2)应该类似于['1+3+4', '3+4', '4+4+3']

我想这就是你想要的

另一项提案Counter

from collections import Counter

strings = ["dog cat mouse", " cat mouse", "mouse mouse cat"]
words_lists = [string.split() for string in strings]
counts = Counter([word for lst in words_lists for word in lst])
result = [sum(counts[word] for word in lst) for lst in words_lists]

结果:

counts: Counter({'mouse': 4, 'cat': 3, 'dog': 1})
result: [8, 7, 11]

相关问题 更多 >