我想知道将文本拆分成句子的有效方法。 句子用点+空格分隔
示例文字
The quick brown fox jumps
over the lazy dog. I love eating toasted cheese and tuna sandwiches.
我的算法就像这样
Read first line from text file to string
Find what is needed
Write to file
然而,有时一半的句子可以在即将到来的行上。
所以我想知道解决这个问题的最佳方法是什么
是的,尝试使用谷歌搜索“多行搜索”,我不想使用正则表达式
最初我的想法是检查第一行是否以.+ space
结束,如果没有抓住另一行并搜索它。但我有一种感觉,我错过了一些东西。
答案 0 :(得分:0)
你可以使用像累加器这样的东西。
1. Read line
2. Check the last symbols in this line.
3. If last symbols are dot or dot+space
3.1 Split it and write all strings to output
3.2 GOTO 1
ELSE
3.3 split the line, write length-1 strings to output
3.4 Keep last piece in some variable and append next readed line to it.
希望我的想法很清楚。
答案 1 :(得分:0)
以下是我解决此问题的方法
void to_sentences()
{
// Do not skip whitespaces
std::cin >> std::noskipws;
char c;
// Loop until there is no input
while (std::cin >> c) {
// Skip new lines
if (c == '\n')
continue;
// Output the character
std::cout << c;
// check if there is a dot folowed by space
// if there add new line
if (c == '.') {
std::cin >> c;
if (c == ' ')
std::cout << endl;
}
}
// Reset skip whitespaces
std::cin >> std::skipws;
}
您可以阅读评论并询问是否有不明确的内容。
答案 2 :(得分:0)
您可以使用std::getline()
,使用自定义分隔符&#39;。&#39;
#include <sstream>
#include <string>
#include <vector>
auto split_to_sentences(std::string inp)
{
std::istringstream ss(inp); // make a stream using the string
std::vector< std::string > sentences; // return value
while(true) {
std::string this_sentence;
std::getline(ss, this_sentence, '.');
if (this_sentence != "")
sentences.push_back(std::move(this_sentence));
else
return sentences;
}
}
请注意,如果您将输入文字作为流,则可以跳过std::stringstream
步骤,并将流直接提供给std::getline
,代替ss
。
使用std::move
不是必需的,但可以通过阻止复制和删除std::string
的动态部分(在堆上)来提高性能。