加权随机选择:根据 .txt 文件中的频率随机生成 "n" 个词的列表

Weighted random choice: Generate a list of "n" words respecting the frequencies in a .txt file randomly

我有一个包含 500 个单词及其各自频率的文本文件。

我需要一个代码来随机生成 "n" 个单词的列表,这些单词与文本文件中的频率有关。

.txt 是这个:

palabrasyfrecuencias.txt

我正在使用此代码读取文件:

pd.read_fwf('palabrasyfrecuencias.txt', header=None, names=["Núm. orden", "Palabras", "Frecuencia"])

这是我现在得到的结果:

欢迎任何帮助。非常感谢!

只需一个利用累积概率的简单数字生成器技巧就可以解决问题。 (请原谅我搞砸了 el Español)。

import random
import pandas as pd

pd.read_fwf('palabrasyfrecuencias.txt', header=None, names=["Núm. orden", "Palabras", "Frecuencia"])
sum(df["Frecuencia"])

# This is actually a count, not a frequency
df["Contar"] = df["Frecuencia"]

# Compute the frequencies as a proportion of the total seen words
df["Frecuencia"] = df["Contar"] / sum(df["Contar"])

# Compute the cumulative distribution
df["Frecuencia_Acumulada"] = df['Frecuencia'].cumsum()


def generate_word(df):
    """
    Generate a word according to the provided cumulative distribution using a random number
    generator.

    Args:
        None
    Returns:
        The generated word
    """
    rand = random.random()

    # The first cumulative frequency in the range is the word we're looking for
    return df[df["Frecuencia_Acumulada"] > rand]["Palabras"].iloc[0]

# Generate N words
N = 10
generated_words = [generate_word(df) for _ in range(N)]