
在处理自然语言处理或文本分析时,通常需要在较大的文本体中搜索特定的单词或短语。一个常见的任务是找到句子中以给定前缀开头的所有单词。在本文中,我们将探讨如何使用C++来完成这个任务。
读取输入的句子和前缀。
将输入的句子分解为单个单词。
For each word in the sentence, check if it starts with the given prefix.
如果单词以该前缀开头,则将其添加到匹配的单词列表中。
打印匹配的单词列表。
#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++完成这个任务。
以上就是从给定的句子中找出以给定词为前缀的词的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号