我怎样才能找到一个句子的n元语法

How can I find the n-gram of a sentence?

本文关键字:一个 句子 元语法      更新时间:2023-10-16

我得到了helloworld的测试字符串,我必须在其中找到n-gram,具体说明它是3。因此,我的代码应该给我以下输出: hel, ell, llo, low, owo, wor, orl, rld,

我编写的代码如下:

vector<string> generate_ngrams(string w, size_t n) {
vector<string> ngrams;
for (auto i = 0; i < n; i++) {
    ngrams.push_back(w.substr(i * n, n));
}
return ngrams; 

我用我的代码得到的输出: hel, low, orl,

例如,我如何操作到目前为止的代码,以便 for 循环调用某种类型的推送回"e",然后找到它后面的两个字母,并继续这样做,直到它不能再这样做了?

这是主要的调用,也是为了看看被扔进去了什么:

  case 2:{
    string s;
    int n;
    cin >> n;
    cin.ignore(100, 'n');    
    getline(cin, s);
    auto v = generate_ngrams(s, n);
    copy (v.begin(), v.end(), oss);
    cout << endl;
    break;
  }

n 是子集的大小,而不是 w 的大小。

for (int i = 0; i <= w.length() - n; ++i)
{
    ngrams.push_back(w.substr(i, n));
}