2012-06-05 56 views
0

我正在尝试预处理一个文本文件,其中每行都是文档的双字母词,并且在该文档中的频率。这里是每行的一个示例:从字典中创建文档 - 术语矩阵

i_like 1 you_know 2 .... not_good 1

我设法建立从整个语料库中的字典。 现在我想逐行阅读语料库并创建词典,创建文档项矩阵,这样矩阵中的每个元素(i,j)就是文档“i”中词项“j”的频率。

+1

我不确定我明白,文档的名称在哪里?或者每个文档都有一个文本文件? – MiMo

+0

文本文件的每一行代表一个文档(因此,整个文本文件是一个文集)并且每个文档的格式都是我在上面的例子中写的。希望现在清楚 – Angel

回答

2

创建使用字典的每个字产生一个整数指数的函数:

Dictionary<string, int> m_WordIndexes = new Dictionary<string, int>(); 

int GetWordIndex(string word) 
{ 
    int result; 
    if (!m_WordIndexes.TryGet(word, out result)) { 
    result = m_WordIndexes.Count; 
    m_WordIndexes.Add(word, result); 
    } 
    return result; 
} 

结果矩阵为:

List<List<int>> m_Matrix = new List<List<int>>(); 

处理的文本文件的每一行产生的一排matrix:

List<int> ProcessLine(string line) 
{ 
    List<int> result = new List<int>(); 
    . . . split the line in a sequence of word/number of occurences . . . 
    . . . for each word/number of occurences . . .{ 
    int index = GetWordIndex(word);  
    while (index > result.Count) { 
     result.Add(0); 
    } 
    result.Insert(index, numberOfOccurences); 
    } 
    return result; 
} 

您一次只读一行文本文件,呼叫ProcessLine(),并将结果列表添加到m_Matrix中。

+0

谢谢MiMo,实际上字典太大了,我决定创建稀疏矩阵来提高效率,但我使用了解决方案背后的想法。谢谢 – Angel

+0

@Anglel:不客气 – MiMo