将英文文本拆分为多个行

Split english text into senteces(multiple lines)

本文关键字:拆分 文本 文文本      更新时间:2023-10-16

我想知道一种将文本拆分为句子的有效方法。 句子由点 + 空格分隔

示例文本

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结尾,如果没有,则抓住另一行并搜索它。但我有一种感觉,我错过了一些东西。

编辑:抱歉忘了提到我正在C++

这样做

你可以使用累加器之类的东西。

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.

希望我的想法很清楚。

这是我解决这个问题的方法

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;
}

您可以阅读评论并询问是否有不清楚的地方。

您可以使用std::getline(),以及自定义分量计'.">

#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的动态部分(堆上(来提高性能。