【发布时间】:2012-09-26 04:48:50
【问题描述】:
目前我正在尝试通过计算 600 个文件(400 封电子邮件和 200 封垃圾邮件)中单词的出现来处理 lingspam dataset。我已经用Porter Stemmer Aglorithm 使每个单词都通用了,我还希望我的结果在每个文件中都标准化,以便进一步处理。但我不确定如何才能做到这一点..
迄今为止的资源
- 8.3. collections — Container datatypes
- How to count co-ocurrences with collections.Counter() in python?
- Bag of Words model
为了获得下面的输出,我需要能够按升序添加文件中可能不存在的项目。
printing from ./../lingspam_results/spmsgb164.txt.out
[('money', 0, 'univers', 0, 'sales', 0)]
printing from ./../lingspam_results/spmsgb166.txt.out
[('money', 2, 'univers', 0, 'sales', 0)]
printing from ./../lingspam_results/spmsgb167.txt.out
[('money', 0, 'univers', 0, 'sales', 1)]
然后我计划使用numpy 转换为vectors。
[0,0,0]
[2,0,0]
[0,0,0]
而不是..
printing from ./../lingspam_results/spmsgb165.txt.out
[]
printing from ./../lingspam_results/spmsgb166.txt.out
[('univers', 2)]
printing from ./../lingspam_results/spmsgb167.txt.out
[('sale', 1)]
如何将Counter 模块中的结果标准化为Ascending Order(同时将我的search_list 中可能不存在的项目添加到计数器结果中)?我已经在下面尝试了一些东西,它只是从每个文本文件中读取并根据search_list 创建一个列表。
import numpy as np, os
from collections import Counter
def parse_bag(directory, search_list):
words = []
for (dirpath, dirnames, filenames) in os.walk(directory):
for f in filenames:
path = directory + "/" + f
count_words(path, search_list)
return;
def count_words(filename, search_list):
textwords = open(filename, 'r').read().split()
filteredwords = [t for t in textwords if t in search_list]
wordfreq = Counter(filteredwords).most_common(5)
print "printing from " + filename
print wordfreq
search_list = ['sale', 'univers', 'money']
parse_bag("./../lingspam_results", search_list)
谢谢
【问题讨论】:
-
“按升序”到底是什么意思?你不是在谈论
search_list单词的字母顺序,是吗? -
或者您希望每个文件的项目按它们在所有文件中的总体频率排序?
-
我说的是
wordfreq = Counter(filteredwords).most_common(5)在ascending order中的结果,而不是哪个单词出现次数最多的顺序。 -
您想对整个
(count, word)值进行升序排序吗?我看不到您上面的第一个示例是如何按升序排列的。另外,它们都在一个大元组中是错字吗?我看不出您的代码如何产生该输出。 -
是的,我注意到我自己在我的例子中,我已经编辑了它。而且我的代码无法产生该输出,这几乎就是我要问的原因,因为我想知道该输出是否可能。问候
标签: python collections preprocessor normalization spam-prevention