c++ - 如何在文件中查找特定单词周围的单词

标签 c++

我的结果文件很大。我想在此文件中查找围绕特定词的词。 例如,如果我有这样一个文件: 我 是 去 家 他们 是 去 学校 山姆 是 去 到 午餐

如何使用 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();
}

关于c++ - 如何在文件中查找特定单词周围的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15371116/

相关文章:

android - 如何为 NDK 转换 C++ 代码?

c++ - 为多处理器查找 DAG 的静态调度 - 库?

c++ - 三元运算符和 if constexpr

c++ - 为什么下面的非静态数据成员初始化在C++11中是无效的

c++ - 具有未知列表模板参数的 QVariant 到 QList

c++ - 计算内存中的二维数组

c++ - 从指向的对象本身有效地释放指针

python - 将类型对象(类,而不是实例)从 python 传递到 c++

c++ - 就像儒略数是用来计算日期有没有具体的数字来计算时间

c++ - 如何检查模板的参数类型是否完整?