首页 > 解决方案 > 如何根据它在文本中出现的概率输出一个单词?

问题描述

假设我有 3 个单词和它们在一段文本中出现的频率。

例如:

是 (1)

不是 (1)

有 (2)

由于所有单词的总频率为 4,因此我生成了一个介于 0-3 或 1-4 之间的随机数。我将如何使用这个随机数,以便程序输出“是”1/4 的时间、“不是”1/4 的时间和“拥有”1/2 的时间?

标签: c++c++11random

解决方案


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)以获取加权概率字符串。


推荐阅读