c++ - 如何根据它在文本中出现的概率输出一个单词?
问题描述
假设我有 3 个单词和它们在一段文本中出现的频率。
例如:
是 (1)
不是 (1)
有 (2)
由于所有单词的总频率为 4,因此我生成了一个介于 0-3 或 1-4 之间的随机数。我将如何使用这个随机数,以便程序输出“是”1/4 的时间、“不是”1/4 的时间和“拥有”1/2 的时间?
解决方案
std::map<unsigned int, std::string> table;
从那开始。
unsigned int total(){
if(table.empty())
return 0;
return table.back().first;
}
void add_word(std::string word, unsigned int count){
unsigned current = total();
table[current+count]=word;
}
现在table
包含一个从字符串的累积权重和所有“之前”到字符串的映射。
std::string pick( unsigned int x ){
return table.lower_bound(x).second;
}
选择一个随机数从1
包含total()
。调用pick(x)
以获取加权概率字符串。
推荐阅读
- c# - 如何在长时间运行期间更新 UI
- azure-devops - 对 Azure DevOps Server 使用自定义工作
- jenkins - 如何使用 Jenkins 将 BitBucket webhook 帖子内容存储到文件中?
- bash - 如何在bash中逃避反引号
- python - 如何在 discord.py 最新版本中分配角色?
- c - 我在 c 中有一个损坏的 while 循环
- javascript - EJS 文件作为静态 HTML 而不是 JS 打开
- javascript - 如何从http请求NodeJS中获取变量?
- google-cloud-platform - 将 GCP 访问的 IP 列入白名单
- java - 如何制作一个正则表达式来匹配以 0-9 或 az 开头的带有重音符号的字符串,并且必须只接受这个特殊字符 - 单词之间的 _ '?