将英文文本拆分为多个行
Split english text into senteces(multiple lines)
我想知道一种将文本拆分为句子的有效方法。 句子由点 + 空格分隔
示例文本
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
的动态部分(堆上(来提高性能。
相关文章:
- 文本文件中的单词链表
- 将英文文本拆分为多个行
- 如何在Qt文本阅读中拆分t
- 如何使用 c++ 逐行处理文本文件并将其参数拆分为变量?
- 如何将文本(诗歌)拆分为行(字符串/字符[])并查找每个行的最后一个单词
- 使用 C++ boost::split 拆分字符串,而不在引号文本内拆分
- 分析示例文本文件并将其拆分
- 如何将XML文件拆分为多个XML,以便每个新文件只包含原始文件中的一个文本节点
- 正在分析文本文件并从中拆分
- 拆分和合并文本
- 将文本输入中的字符串拆分为更小的字符串
- c++如何将文本文件中的一行拆分为两行,然后将每行存储到两个不同的数组中
- 将大型数据文件拆分为多个小文件(文本格式)
- 将文本文件拆分为多个文件 c++
- 通过使用分隔符C++拆分文本来制作 2D 数组
- 将单独文本文件的段落拆分为单独的字符串
- 当找到某个令牌时,是否有更快的方法来拆分文本文件
- 如何从文本文件中读取并在C中拆分句子
- 使用正则表达式在Embarcadero的C++生成器中将文本拆分为单个单词
- 使用ICU将文本拆分为单词列表