首页 > 解决方案 > 如何从生成随机字母集的代码中提取真实单词

问题描述

我想找出在一组随机生成的字母中出现的真实单词的平均数量。有没有一种pythonic方法可以做到这一点?

我已经设法弄清楚如何生成一组 1000 个随机字母 1000 次,但我不知道如何有效地计算真实单词的数量。

这是我到目前为止所拥有的

Potato=0

import string
import random
def text_gen(size=100, chars=string.ascii_uppercase + string.ascii_lowercase):
    return ''.join(random.choice(chars) for _ in range(size))

while True:
    print (text_gen(1000))
    Potato=Potato+1
    if Potato==1001:
        break

从生成的字符串中,我如何才能只过滤掉有意义的部分?

标签: python

解决方案


您可以采取不同的路线;将单词的数量除以可能的组合。

从字典中创建一组给定长度的单词,例如 6 个字母:

with open('words.txt') as words:
    six_letters = {word for word in words.read().splitlines()
                   if len(word) == 6}

六个字母单词的数量是len(six_letters)

六个小写字母的组合数量是26 ** 6

所以得到一个有效的六个字母单词的概率是:

len(six_letters) / 26 ** 6

编辑:Python 2 使用地板除法,所以会给你0.

您可以将分子或分母转换为 afloat以获得非零结果,例如:

len(six_letters) / 26.0 ** 6

或者,您可以通过从未来导入使您的 Python 2 代码表现得像 Python 3:

from __future__ import division

len(six_letters) / 26 ** 6

哪一个,用你的单词列表,都给我们:

9.67059707562e-05

4个字母单词的数量是7185。在标准库中有一个很好的收集直方图数据的工具,collections.Counter

from collections import counter
from pprint import pprint

with open(words_file) as words:
    counter = Counter(len(word.strip()) for word in words)

pprint(counter.items())

您文件中的值给出:

[(1, 26),
 (2, 427),
 (3, 2130),
 (4, 7185),
 (5, 15918),
 (6, 29874),
 (7, 41997),
 (8, 51626),
 (9, 53402),
 (10, 45872),
 (11, 37538),
 (12, 29126),
 (13, 20944),
 (14, 14148),
 (15, 8846),
 (16, 5182),
 (17, 2967),
 (18, 1471),
 (19, 760),
 (20, 359),
 (21, 168),
 (22, 74),
 (23, 31),
 (24, 12),
 (25, 8),
 (27, 3),
 (28, 2),
 (29, 2),
 (31, 1)]

因此,53402您的字典中的大多数单词 , 都有9字母。大约有字母的5两倍,字母单词4的两倍。65


推荐阅读