Skip to content

Instantly share code, notes, and snippets.

@paddy74
Created April 17, 2019 21:35
Show Gist options
  • Select an option

  • Save paddy74/6ac50d6ee08c6854e869493fc6fd026a to your computer and use it in GitHub Desktop.

Select an option

Save paddy74/6ac50d6ee08c6854e869493fc6fd026a to your computer and use it in GitHub Desktop.
A simple function for the collection of ngrams for a vector of strings.
/**
* MIT License
*
* Copyright (c) 2019 Patrick Cox
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <string>
#include <vector>
/**
* @brief Construct ngrams for the given ordered token vector.
*
* @param tokenVect Ordered token vector from which to construct ngrams.
* @param n Size of max ngram. All lesser ngrams are also collected.
* @return std::vector<std::string>
*/
std::vector<std::string> ngramify(
std::vector<std::string> const & tokenVect,
uint const & n
)
{
// TODO: infinite grams (recursive)
std::vector<std::string> ngramVect;
for (
auto tokenItr = tokenVect.begin();
tokenItr < tokenVect.end()-1;
++tokenItr)
{
// 1-gram
ngramVect.push_back(*tokenItr);
// 2-gram
if (n >= 2)
{
auto const & next1 = tokenItr + 1;
if (next1 != tokenVect.end())
ngramVect.push_back(*tokenItr + ' ' + *next1);
// 3-gram
if (n >= 3)
{
auto const & next2 = next1 + 1;
if (next2 != tokenVect.end())
ngramVect.push_back(*tokenItr + ' ' + *next1 + ' ' + *next2);
}
}
}
return ngramVect;
}
/**
* @brief Construct ngrams for the given ordered token vector inplace.
*
* @param tokenVect Ordered token vector from which to construct ngrams.
* @param n Size of max ngram. All lesser ngrams are also collected.
*/
void ngramifyInplace(
std::vector<std::string> & tokenVect,
uint const & n
)
{ tokenVect = ngramify(tokenVect, n); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment