如何在C++中正确解析带有多个分隔符的文本文件

How do I properly parse a text file with multiple delimiters in C++?

本文关键字:分隔符 文件 文本 C++      更新时间:2023-10-16

我必须将一个带有段落的输入文件解析为句子。输出中的每一行对应一个句子。这基本上是对的,但我不能得到想要的结果。

我被要求使用的分隔符是:

  • 。">
  • ?">

测试输入:第一个故事是关于连接点。

前6个月后,我从里德学院退学,但在我真正辞职之前,我又在这里待了18个月左右。那我为什么要退学呢?

它始于我出生之前。我的生母是一名年轻的未婚大学生,她决定收养我。她非常强烈地认为我应该被大学毕业生收养,所以一切都准备好了,我一出生就被一位律师和他的妻子收养。只是当我突然出现时,他们在最后一刻决定他们真的想要一个女孩。因此,我的父母在等待名单上,半夜接到一个电话,问:"我们有一个意想不到的男婴,你想要他吗?"他们说:"当然。"我的亲生母亲后来发现,我母亲从未从大学毕业,我父亲也从未从高中毕业。她拒绝在最后的领养文件上签字。几个月后,当我父母答应我有一天会上大学时,她才松口。

#include "FileIOs_WordPairs.h"
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;
bool sentenceSplitter(string& fname, vector<string>& sentences)
{
ifstream file;
string temp;
size_t pos = 0;
string token;
file.open(fname);
if (file.fail())
{
cerr << "Failed to open the file" << endl;
return(-1);
}
while (getline(file, temp))
{
istringstream iss(temp);
while ((pos = temp.find_first_of(".")) != string::npos)
{
token = temp.substr(0, pos);
if (token.length() != 0)
cout << token << endl;
temp = temp.substr(pos + strlen("."));
}
while ((pos = temp.find_first_of("?")) != string::npos)
{
token = temp.substr(0, pos);
if (token.length() != 0)
cout << token << endl;
temp = temp.substr(pos + strlen("?"));
}
while ((pos = temp.find_first_of("."")) != string::npos)
{
token = temp.substr(0, pos);
if (token.length() != 0)
cout << token << endl;
temp = temp.substr(pos + strlen(".""));
}
while ((pos = temp.find_first_of("?"")) != string::npos)
{
token = temp.substr(0, pos);
if (token.length() != 0)
cout << token << endl;
temp = temp.substr(pos + strlen("?""));
}
}
}

预期输出:

  • 第一个故事是关于连接点
  • 前6个月后,我从里德学院退学,但在我真正退学之前,我又在这里待了18个月左右
  • 那我为什么要退学
  • 它始于我出生之前
  • 我的生母是一名年轻的未婚大学研究生,她决定收养我
  • 她非常强烈地认为我应该被大学毕业生收养,所以一切都准备好了,我一出生就被一位律师和他的妻子收养
  • 只是当我突然出现时,他们在最后一刻决定他们真的想要一个女孩
  • 因此,我的父母在等待名单上,半夜接到一个电话,问:"我们有一个意想不到的男婴,你想要他吗?">
  • 他们说:"当然
  • 我的亲生母亲后来发现,我母亲从未从大学毕业,我父亲也从未从高中毕业
  • 她拒绝在最后的领养文件上签字
  • 几个月后,当我父母答应我有一天会上大学时,她才松口

当前输出:

  • 第一个故事是关于连接点
  • 前6个月后,我从里德学院退学,但在我真正退学之前,我又在这里待了18个月左右
  • 那我为什么要退学
  • 它始于我出生之前
  • 我的生母是一名年轻的未婚大学研究生,她决定收养我
  • 她非常强烈地认为我应该被大学毕业生收养,所以一切都准备好了,我一出生就被一位律师和他的妻子收养
  • 只是当我突然出现时,他们在最后一刻决定他们真的想要一个女孩
  • 因此,我的父母在等待名单上,半夜接到一个电话,问:"我们有一个意想不到的男婴,你想要他吗?"他们说:"当然。">
  • "我的亲生母亲后来发现,我母亲从未从大学毕业,我父亲也从未从高中毕业
  • 她拒绝在最后的领养文件上签字
  • 几个月后,当我父母答应我有一天会上大学时,她才松口

简单地说,我找不到使用的方法。"和?"作为分隔符

使用boost库,很容易:

#include <iostream>
#include <string>
#include <boost/algorithm/string/regex.hpp>
int main()
{
using namespace std;
vector< string > results;
std::string text = "Hi! How are you?? Today is a nice day.";
boost::algorithm::split_regex( results, text, boost::regex( "\!|\.|\?\?" ) ) ;
for(string sentence:results)
std::cout << "[" << sentence << "]" << std::endl;
}

编译:

g++ -std=c++11 main.cpp -lboost_regex  && ./a.out

结果:

[Hi]
[ How are you]
[ Today is a nice day]
[]