【发布时间】:2016-07-19 17:48:48
【问题描述】:
我正在尝试计算文本文件中特定单词的出现次数,问题是当我的代码读取文件时 - 它使用空格分隔符读取它,但我想要计算的一些单词是“ 2字词”例如“out from”
除此之外,还有第二个问题,那就是“不是”和“不要”之类的词——即使我在地图中用反斜杠放置它们,我的代码似乎也忽略了这些词——我的猜测是由于某种原因,它在从文件中读取它的过程中被忽略了
我正在寻找的最终结果是我正在搜索的单词的频率。
std::list<std::string> Fwords = {
"a","abroad","as far as","ahead of"};
// Begin reading from file:
std::ifstream fileStream(fileName);
// Check if we've opened the file (as we should have).
if (fileStream.is_open())
while (fileStream.good())
{
// Store the next word in the file in a local variable.
std::string word;
fileStream >> word;
std::cout << "This is the word: " << word << endl;
if (std::find(std::begin(Fwords), std::end(Fwords), word) != std::end(Fwords))
wordsCount[word]++;
}
输入:
"ahead of me as far as abroad me"
这将是预期的输出:
abroad:1
ahead of:1
as far as:1
【问题讨论】:
-
所以你说“as far as”应该被视为一个词?
-
你能发一个minimal reproducible example吗?我们不需要查看您要计算的所有单词
-
@LogicStuff,他可以,这只是一个空操作。
-
如果您只想完成工作,请使用
std::regex_search。 -
您的条目真的是独一无二的吗?所以我的意思是,您是否分别检测到
"out from"、"out"和"from"?可能@LogicStuff 的提议目前看来是最合适的。