Select 列表中的元素使用 python 中类似 Zipf 的选择
Select elements from list using a Zipf-like selection in python
是否可以 select 使用 python 遵循 Zipf 分布的列表中的一个元素?
假设我有一个列表:
objlist = ['Here', 'in', 'the', 'wall', 'why']
到目前为止,我已经看过https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.zipf.html
但我想不出解决办法。
提前致谢。
只需使用 numpy.random.zipf(shape_parameter)
的输出作为列表的索引。但是存在一个问题,即 zipf 分布是未绑定的,并且该值可能大于您的索引。所以将其插入 try:
except:
块中。
当您多次 运行 您的代码时,将从您的列表中提取不同的值。但是,由于 zipf 分布是未绑定的,而您的列表索引不是,因此不会完全是 zipf 分布。
萨普尔代码:
objlist = ['Here', 'in', 'the', 'wall', 'why']
index = np.random.zipf([1.2, 1.2])
for idx in index:
if idx < len(objlist):
print(objlist[idx])
else:
print "Index {} exceed list".format(idx)
希望我没有误解您的要求,这是我的代码:
import random
objlist = ['Here', 'in', 'the', 'wall', 'why']
print random.choice(objlist)
要select 根据实际经验Zipf分布,首先需要一个table的英文单词出现频率。如果最频繁的 100,000 个你可以得到一个 here.
那个是pdf,文字比较好处理,转一下,linux就可以了
pdftotext freq100000.pdf
这将创建一个文本文件 freq100000.txt,您可以将其与以下小脚本一起使用
import re
import numpy as np
record = re.compile('[0-9]+ [0-9]+ [a-z]+')
data = {}
for line in open('freq100000.txt'):
m = record.match(line.strip())
if not m is None:
rank, freq, word = m.group(0).split()
data[word] = int(rank), int(freq)
def rel_freqs(wlist):
freqs = np.array([data[word.lower()][1] for word in wlist])
ps = np.add.accumulate(freqs)
choice = np.searchsorted(ps, np.random.randint(ps[-1]))
return choice
rel_freqs(['Here', 'in', 'the', 'wall', 'why'])
函数 rel_freqs
从列表中随机 select 一个词,returns 它的索引。抽到一个词的概率与其在英语中出现的频率成正比。
是否可以 select 使用 python 遵循 Zipf 分布的列表中的一个元素?
假设我有一个列表:
objlist = ['Here', 'in', 'the', 'wall', 'why']
到目前为止,我已经看过https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.zipf.html 但我想不出解决办法。
提前致谢。
只需使用 numpy.random.zipf(shape_parameter)
的输出作为列表的索引。但是存在一个问题,即 zipf 分布是未绑定的,并且该值可能大于您的索引。所以将其插入 try:
except:
块中。
当您多次 运行 您的代码时,将从您的列表中提取不同的值。但是,由于 zipf 分布是未绑定的,而您的列表索引不是,因此不会完全是 zipf 分布。
萨普尔代码:
objlist = ['Here', 'in', 'the', 'wall', 'why']
index = np.random.zipf([1.2, 1.2])
for idx in index:
if idx < len(objlist):
print(objlist[idx])
else:
print "Index {} exceed list".format(idx)
希望我没有误解您的要求,这是我的代码:
import random
objlist = ['Here', 'in', 'the', 'wall', 'why']
print random.choice(objlist)
要select 根据实际经验Zipf分布,首先需要一个table的英文单词出现频率。如果最频繁的 100,000 个你可以得到一个 here.
那个是pdf,文字比较好处理,转一下,linux就可以了
pdftotext freq100000.pdf
这将创建一个文本文件 freq100000.txt,您可以将其与以下小脚本一起使用
import re
import numpy as np
record = re.compile('[0-9]+ [0-9]+ [a-z]+')
data = {}
for line in open('freq100000.txt'):
m = record.match(line.strip())
if not m is None:
rank, freq, word = m.group(0).split()
data[word] = int(rank), int(freq)
def rel_freqs(wlist):
freqs = np.array([data[word.lower()][1] for word in wlist])
ps = np.add.accumulate(freqs)
choice = np.searchsorted(ps, np.random.randint(ps[-1]))
return choice
rel_freqs(['Here', 'in', 'the', 'wall', 'why'])
函数 rel_freqs
从列表中随机 select 一个词,returns 它的索引。抽到一个词的概率与其在英语中出现的频率成正比。