好吧,在我问我的问题之前,我想弄清楚一件事。我目前是 NIU 计算机科学专业的学生,这确实与我在那里的一门课的作业有关。因此,如果有人有问题,请继续阅读并继续您的业务。
现在对于任何愿意提供帮助的人来说都是这种情况。对于我当前的任务,我们必须读取一个只是一段文本的文件。对于文件中的每个单词,我们要清除单词中的任何标点符号(例如:“can't”最终会变成“can”,而“that--to”最终会变成“that”,显然没有引号,引号仅用于指定示例是什么)。
我遇到的问题是,我可以很好地清理字符串,然后将其插入到我们正在使用的映射中,但出于某种原因,我编写的代码允许将空字符串插入到 map 。现在我已经尝试了所有我能想出的办法来阻止这种情况发生,我唯一想到的就是在映射结构本身中使用删除方法。
所以我正在寻找的是两件事,关于我如何能够 a) 解决这个问题而不仅仅是删除它的任何建议,以及 b) 我可以对我已经编写的代码进行的任何改进。
这是我编写的函数,用于从文件中读入,然后是清理文件的函数。
注意:从文件中读入的函数调用 clean_entry 函数以在将任何内容插入 map 之前去除标点符号。
编辑:谢谢克里斯。允许使用数字 :)。如果有人对我编写的代码有任何改进或对我所做的事情有任何批评,我会倾听。在学校里,我们真的得不到有关正确、适当或最有效的做事方式的反馈。
int get_words(map<string, int>& mapz)
{
int cnt = 0; //set out counter to zero
map<string, int>::const_iterator mapzIter;
ifstream input; //declare instream
input.open( "prog2.d" ); //open instream
assert( input ); //assure it is open
string s; //temp strings to read into
string not_s;
input >> s;
while(!input.eof()) //read in until EOF
{
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() == 0)
{
input >> s;
clean_entry(s, not_s);
}
mapz[not_s]++; //increment occurence
input >>s;
}
input.close(); //close instream
for(mapzIter = mapz.begin(); mapzIter != mapz.end(); mapzIter++)
cnt = cnt + mapzIter->second;
return cnt; //return number of words in instream
}
void clean_entry(const string& non_clean, string& clean)
{
int i, j, begin, end;
for(i = 0; isalnum(non_clean[i]) == 0 && non_clean[i] != '\0'; i++);
begin = i;
if(begin ==(int)non_clean.length())
return;
for(j = begin; isalnum(non_clean[j]) != 0 && non_clean[j] != '\0'; j++);
end = j;
clean = non_clean.substr(begin, (end-begin));
for(i = 0; i < (int)clean.size(); i++)
clean[i] = tolower(clean[i]);
}
最佳答案
空条目的问题出在您的 while 循环中。如果你得到一个空字符串,你清理下一个字符串,并在不检查的情况下添加它。尝试更改:
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() == 0)
{
input >> s;
clean_entry(s, not_s);
}
mapz[not_s]++; //increment occurence
input >>s;
到
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() > 0)
{
mapz[not_s]++; //increment occurence
}
input >>s;
编辑:我注意到您正在检查字符是否为字母数字。如果不允许使用数字,您可能还需要重新访问该区域。
关于c++ - 在 C++ 中清理一串标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/116469/