如何在文件中找到特定单词周围的单词

How to find words around a particular word in a file

本文关键字:单词周 单词 文件      更新时间:2023-10-16

我的结果中有一个大文件。我想在这个文件中查找一个特定单词周围的单词。例如,如果我有一个这样的文件:我我会首页他们是会学校山姆是会来午餐

如何使用c++获取"going"前后的单词并将其保存在散列中

您可以一个字一个字地读取文件,始终保持N个字作为上下文。您可以将上下文存储在允许滚动上下文的std::deque

const int N = 10;
std::deque<std::string> words_before, words_after;
std::string current_word, w;
// prefetch words before and after
for (int i = 0; i < N; ++i) {
    std::cin >> w;
    words_before.push_back(w);
}
std::cin >> current_word;
for (int i = 0; i < N - 1; ++i) {
    std::cin >> w;
    words_after.push_back(w);
}
// now process the words and keep reading
while (std::cin >> w) {
    words_after.push_back(w);
    // save current_word with the words around words_before, words_after
    words_before.pop_front();
    words_before.push_back(current_word);
    current_word = words_after.front();
    words_after.pop_front();
}