问题 将boost :: tokenizer与字符串分隔符一起使用


我一直在寻找boost :: tokenizer,我发现文档很薄。是否有可能将其标记为“dolphin - monkey - baboon”这样的字符串并将每个单词作为一个标记,以及每个双重标记都是一个标记?从示例中我只看到允许单个字符分隔符。库是否不够先进,无法使用更复杂的分隔符?


10943
2017-08-09 20:38


起源

只是好奇为什么这是标记社区维基? - Adam Batkin
我认为这会让其他人澄清我的问题,以防它有点分散。也许我应该读到它是什么,直到下一次。 - Martin


答案:


看起来你需要自己编写 TokenizerFunction 做你想做的事。


0



我懂了。我希望有预制的东西,但我想我希望得到太多。 - Martin


使用iter_split可以使用多个字符标记。 下面的代码将产生以下内容:

  海豚
  猴
  狒狒

#include <iostream>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/iter_find.hpp>

    // code starts here
    std::string s = "dolphin--mon-key--baboon";
    std::list<std::string> stringList;
    boost::iter_split(stringList, s, boost::first_finder("--"));

    BOOST_FOREACH(std::string token, stringList)
    {    
        std::cout << token << '\n';  ;
    }

10



这有创建整个字符串副本的缺点。如果被标记化的字符串很大,这是一个问题。 boost tokenizer不会这样做。 - The Science Boy


我知道主题已经很老了,但是当我搜索“按字符串提升标记器”时,它显示在谷歌的顶部链接中

所以我将添加我的TokenizerFunction变种,以防万一:

class FindStrTFunc
{
public:
    FindStrTFunc() : m_str(g_dataSeparator)
    {
    }

    bool operator()(std::string::const_iterator& next,
        const std::string::const_iterator& end, std::string& tok) const
    {
        if (next == end)
        {
            return false;
        }
        const std::string::const_iterator foundToken =
            std::search(next, end, m_str.begin(), m_str.end());
        tok.assign(next, foundToken);
        next = (foundToken == end) ? end : foundToken + m_str.size();
        return true;
    }

    void reset()
    {
    }

private:
    std::string m_str;
};

我们可以创造

boost::tokenizer<FindStrTFunc> tok("some input...some other input");

并使用,像通常的增强标记器


2



实现不理想(可能有bug),这只是一个例子 - Alek86


一种选择是尝试boost :: regex。与自定义标记生成器相比,不确定性能。

std::string s = "dolphin--monkey--baboon";

boost::regex re("[a-z|A-Z]+|--");
boost::sregex_token_iterator iter(s.begin(), s.end() , re, 0);
boost::sregex_token_iterator end_iter;

while(iter != end_iter)
{
    std::cout << *iter << '\n';
    ++iter;
}

1



这很好。如果它有效,它就会得到我的投票。 :) - The Science Boy