【发布时间】:2014-04-13 08:45:38
【问题描述】:
我正在读取一个文本文件并将这些单词解析为一个映射,以计算每行中每个单词的出现次数。我需要忽略除撇号之外的所有非字母字符(标点符号、数字、空格等)。我可以使用以下代码弄清楚如何删除所有这些字符,但这会导致错误的单词,例如“one-two”出现为“onetwo”,应该是两个单词,“one”和“two”。
相反,我现在尝试用空格替换所有这些值,而不是简单地删除,但不知道如何做到这一点。我认为 replace-if 算法将是一个很好的算法,但无法找出正确的语法来完成此操作。 C++11 没问题。有什么建议吗?
示例输出如下:
"first second" = "first" and "second"
"one-two" = "one" and "two"
"last.First" = "last" and "first"
"you're" = "you're"
"great! A" = "great" and "A"
// What I initially used to delete non-alpha and white space (apostrophe's not working currently, though)
// Read file one line at a time
while (getline(text, line)){
istringstream iss(line);
// Parse line on white space, storing values into tokens map
while (iss >> word){
word.erase(remove_if(word.begin(), word.end(), my_predicate), word.end());
++tokens[word][linenum];
}
++linenum;
}
bool my_predicate(char c){
return c == '\'' || !isalpha(c); // This line's not working properly for apostrophe's yet
}
【问题讨论】: