将句子标记为单词,考虑特殊字符
Tokenize sentence into words, considering special characters
我有一个函数,它接收一个句子,并根据空格"标记成单词" "。现在,我想改进功能以消除一些特殊字符,例如:
I am a boy. => {I, am, a, boy}, no period after "boy"
I said :"are you ok?" => {I, said, are, you, ok}, no question and quotation mark
原来的功能在这里,我该如何改进它?
void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ")
{
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
}
您可以使用
std::regex
.在那里,您可以搜索任何您想要的内容,然后将结果放入向量中。这很简单。
看:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <regex>
// Our test data (raw string). So, containing also " and so on
std::string testData(R"#(I said :"are you ok?")#");
std::regex re(R"#((bw+b,?))#");
int main(void)
{
// Define the variable id as vector of string and use the range constructor to read the test data and tokenize it
std::vector<std::string> id{ std::sregex_token_iterator(testData.begin(), testData.end(), re, 1), std::sregex_token_iterator() };
// For debug output. Print complete vector to std::cout
std::copy(id.begin(), id.end(), std::ostream_iterator<std::string>(std::cout, " "));
return 0;
}
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 转换特殊字符(UTF-8)
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何在C++中打印此"█"特殊字符?
- c++为什么ifstream get()函数返回无法识别的特殊字符
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 转义std::字符串中的特殊字符
- SDL2加载具有特殊字符的文件
- 将 std::string 转换为具有特殊字符的 FString (TCHAR / wstring)
- 如何从文本文件C++读取整数和特殊字符
- USB序列号显示特殊字符
- 键入特殊字符并保存在文件中
- 回文,不包括特殊字符和空格
- 无法使用 Unicode 特殊字符设置窗口文本
- 使用 libmysql 插入特殊字符
- 使用具有特殊字符的正则表达式标记 C++ 字符串
- 如何输入以特殊字符开头的字符串
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- C++降低特殊字符,例如 ü
- 将句子标记为单词,考虑特殊字符