如何在文件中找到特定词周围的词 [英] How to find words around a particular word in a file

查看:131
本文介绍了如何在文件中找到特定词周围的词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的结果中有一个大文件。我想在这个文件中寻找围绕特定单词的单词。
例如,如果我有一个这样的文件:
I
am

home
他们


school
sam



午餐

I have a big file in my results. I want to look for words around a specific word in this file. For example, if I have a file like this: I am going home they are going school sam is going to lunch

推荐答案

您可以通过单词读取文件,总是保持N个词作为上下文。您可以将上下文存储在 std :: deque 允许滚动上下文

You can just read the file word by word, always keeping N words as context. You can store the context in a std::deque which allows a rolling context

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();
}

这篇关于如何在文件中找到特定词周围的词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆