使用Octave计算数千个文本文件中最常用的单词



我在Octave中积累了超过10,000个文本文件的列表。我有一个函数,它清理每个文件的内容,以各种方式规范化(小写字母,减少重复的空白等)。我想从所有这些文件中提取出至少在100个文件中出现的单词列表。我一点也不熟悉Octave数据结构或单元数组或Octave排序函数,希望有人能帮助我理解如何:

  1. 初始化适当的数据结构(word_appearance)来计算包含特定单词的电子邮件数量
  2. 循环出现在电子邮件字符串中的唯一单词,并为每个单词增加我在word_appearance中跟踪的计数——理想情况下,我们会忽略长度少于两个字符的单词,并排除stop_words的短列表。
  3. 减少word_appearance以只包含出现一定次数的单词,例如,min_appearance =100次。
  4. 按字母顺序对word_appearance中的单词进行排序,并将其导出为.MAT文件或CSV文件,如下所示:
1    aardvark
2    albatross

等。

我现在有这段代码来逐个遍历我的文件:

for i = 1:total_files
filename = char(files{i}(1));
printf("processing %sn", filename);
file_contents = jPreProcessFile(readFile(filename)) 
endfor

请注意,返回的file_contents非常干净——通常只是一堆单词,有些是重复的,用单个空格分隔,就像这样:

email market if done right is both highli effect and amazingli cost effect ok it can be downright profit if done right imagin send your sale letter to on million two million ten million or more prospect dure the night then wake up to sale order ring phone and an inbox full of freshli qualifi lead we ve been in the email busi for over seven year now our list ar larg current and deliver we have more server and bandwidth than we current need that s why we re send you thi note we d like to help you make your email market program more robust and profit pleas give us permiss to call you with a propos custom tailor to your busi just fill out thi form to get start name email address phone number url or web address i think you ll be delight with the bottom line result we ll deliv to your compani click here emailaddr thank you remov request click here emailaddr licatdcknjhyynfrwgwyyeuwbnrqcbh

显然,我需要创建word_appearance数据结构,使其中的每个元素指定一个单词以及到目前为止包含该单词的文件数量。我的主要困惑点是word_appearance应该是什么样的数据结构,我该如何搜索这个数据结构,看看其中是否已经有一些新单词,如果找到,增加它的计数,否则在word_appearance中添加一个新的元素,count=1。

Octave有containers.Map来保存键值对。下面是简单的用法:

% initialize map
m = containers.Map('KeyType', 'char', 'ValueType', 'int32');
% check if it has a word
word = 'hello';
if !m.isKey(word)
m(word) = 1;
endif
% increment existing values
m(word) += 1;

这是一种从像上面这样的映射中提取最频繁单词的方法:

counts = m.values;
[sorted_counts, indices] = sort(cell2mat(counts));
top10_indices = indices(end:-1:end-9);
top10_words = m.keys(top10_indices);

我必须警告你,考虑到你有成千上万的文件,Octave在这个任务中可能会很慢。只有当运行时间对你来说不是那么重要的时候才使用它。

最新更新