如何对文本文件中的信息进行哈希处理

How to hash information from a text file?

本文关键字:信息 哈希 处理 文本 文件      更新时间:2023-10-16

我试图做的是从文本文件中读取一行,将其分解为构成它的单词,然后根据我不想散列的"坏单词"列表检查每个单词。每个不在坏词列表中的"好词"都应该被散列并在其索引中存储整(如果这有意义的话)。因此,例如,"火环"将被拆分为"环"、"的"和"火"。我会散列"环"并存储"火环",我会看到"的"并注意到这是一个不好的词并跳过它,最后我会散列"火"并存储"火环"也用它。

我的代码按原样将一行分成单词,将其与坏词进行比较,并显示所有好词。然后,它关闭文件,重新打开它,并显示所有行。我在概念化时遇到的麻烦是如何将两者结合起来,同时对所有好词和整行进行哈希处理,以便我可以轻松存储它们。我应该怎么做?

#include <cstring>
#include <cctype>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    const char * bad_words[] = {"of", "the", "a", "for", "to", "in", "it", "on", "and"};
    ifstream file;
    file.open("songs.txt");
    //if(!file.is_open()) return;
    char word[50];
while(file >> word)
{
    // if word == bad word, dont hash
    // else hash and store it in my hash table
    bool badword = false;
    for(int i = 0; i < 9; ++i)
    {
        if(strcmp(word, bad_words[i]) == 0)
        {
            badword = true;
        }
    }
    if(badword) continue;
    else
    {
        // get all words in a line that are not in bad_words
        char * good_word = new char[strlen(word)+1];
        strcpy(good_word, word);
        cout << good_word << endl;  // testing to see if works      
        // hash each good_word, store good_line in both of them
        //int index = Hash(good_word);
        //Add(good_line) @ table[index];
    }
}
file.close();
file.open("songs.txt");
while(!file.eof())  // go through file, grab each whole line. store it under the hash of good_word (above)
{
    char line[50];
    file.getline(line, 50, 'n');
    char * good_line = new char[strlen(line)+1];
    strcpy(good_line, line);
    cout << good_line << endl;  // testing to see if works
}
return 0;
}

您似乎正在寻找std::unordered_multimap.

我可能还会对一组"坏"词进行排序,并使用std::binary_search来查看它是否包含特定单词。

std::vector<std::string> bad { "a", "and", "for" /* ... keep sorted */};
std::unordered_multimap<std::string, std::string> index;
while (std::getline(infile, line)) {
    std::istringstream buf(line);
    std::string word;
    while (buf >> word)
       if (!binary_search(bad.begin(), bad.end(), word))
           index.insert(std::make_pair(word, line));
}

如果你真的必须实现自己的哈希表,你可以在这里找到哈希表数据结构的描述。

在最简单的形式中,哈希表是链表的数组。数组使用 hascode % arraySize 进行索引,链表负责哈希冲突。