卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

从给定的句子中找出以给定词为前缀的词

从给定的句子中找出以给定词为前缀的词

在处理自然语言处理或文本分析时,通常需要在较大的文本体中搜索特定的单词或短语。一个常见的任务是找到句子中以给定前缀开头的所有单词。在本文中,我们将探讨如何使用C++来完成这个任务。

算法

  • 读取输入的句子和前缀。

  • 将输入的句子分解为单个单词。

  • For each word in the sentence, check if it starts with the given prefix.

  • 如果单词以该前缀开头,则将其添加到匹配的单词列表中。

  • 打印匹配的单词列表。

Example

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
   string sentence, prefix;
   vector<string> words;
   
   // Read in the input sentence and prefix
   sentence="The quick brown fox jumps over the lazy dog";
   prefix="fox";
   
   // Tokenize the input sentence into individual words
   string word = "";
   for (auto c : sentence) {
      if (c == ' ') {
         words.push_back(word);
         word = "";
      }
      else {
         word += c;
      }
   }
   words.push_back(word);

   // Find all words in the sentence that start with the given prefix
   vector<string> matches;
   for (auto w : words) {
      if (w.substr(0, prefix.length()) == prefix) {
         matches.push_back(w);
      }
   }
   
   // Print the list of matching words
   cout << "Matching words:" << endl;
   for (auto m : matches) {
      cout << m << endl;
   }
   
   return 0;
}

输出

Matching words:
fox

测试用例示例

Suppose we have the following input sentence:

The quick brown fox jumps over the lazy dog

我们想要找到所有以前缀“fox”开头的单词。使用上述代码运行此输入将产生以下输出:

在这个例子中,句子中唯一以前缀"fox"开头的单词是"fox"本身,因此它是唯一被打印为匹配的单词。

结论

在自然语言处理和文本分析中,找到句子中以给定前缀开头的所有单词是一个有用的任务。通过将输入句子分词为单个单词,并检查每个单词是否与前缀匹配,我们可以很容易地使用C++完成这个任务。

卓越飞翔博客
上一篇: 扩展 Drupal 8 Mail API 的功能:第 1 部分
下一篇: 给定一个字符串,将其组成的所有可能长度的字符串都列出来
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏