从文件中阅读句子,并将每个句子分成两个单词短语

Reading sentences from a file and splitting each of them into two word phrases.

本文关键字:句子 短语 单词 两个 文件      更新时间:2023-10-16

我正在打印重复项,并希望删除代码以读取句子,直到文件末尾,并删除多余的空格。

我用这个代码把每个句子分成单词。

vector <string> oneWordPhrase;
vector <string> twoWordPhrase;
vector<string>::iterator it1;
vector<string>::iterator it2;
string split = str;
string word;
stringstream stream(split);
while( getline(stream, word, ' ') )
{
cout<<word<<endl;
oneWordPhrase.push_back(word);
}//split the sentence into words
for(it1=oneWordPhrase.begin(); it1!=oneWordPhrase.end(); it1++) /* the problem 
{                                                    is here. */
if(it1+1 == oneWordPhrase.end())
break; //signal break if we are near the end of a sentence
twoWordPhrase.push_back(*it1 + ' ' + *(it1+1));
}
for(int i=0; i<twoWordPhrase.size(); i++)
cout<<twoWordPhrase[i]<<endl

这个代码只适用于一句话。例如,如果我的字符串是"你好,我叫鲍勃。我是一名学生。"我想打印

"你好,我的">

"我的名字">

"name is">

"is bob">

/*新句子*/

"我是">

"我是">

"学生">

然而,我的输出是

"你好,我的">

"我的名字">

"name is">

"is bob">

/*这里的问题。它回到句子的开头*/

"你好,我的">

"我的名字">

"name is">

"is bob">

"bob i">

/*它也不识别新句子*/

"我是">

"我是">

"学生">

有没有一种方法可以让我使用迭代器来指向它停止的地方,而不是开始。这段代码适用于一句话,但它会创建一个以上字符串的重复

您没有正确检测句子的结尾。

if(it1+1 == oneWordPhrase.end())
break; //signal break if we are near the end of a sentence

只有当你到达整个短语的末尾时,才会触发上面的行。不仅仅是一句话。要检测一个句子,你需要检测句号。这里有一种可能的方法:

for (it1 = oneWordPhrase.begin(); it1 + 1 != oneWordPhrase.end(); it1++) {
if (it1[0][(it1[0].size() - 1)] == '.') {
continue;
}
twoWordPhrase.push_back(*it1 + ' ' + *(it1 + 1));
}

我将it1 != oneWordPhrase.end()更改为it1 + 1 != oneWordPhrase.end(),以模拟break语句的行为。

it1[0][(it1[0].size() - 1)]

提取您存储的单词的最后一个字符。