[英]python get all possible words from list of alphabets
Lets say I have some alphabets and numbers in my text file alphabets.txt
假设我的文本文件中的
alphabets.txt
和数字有一些字母和数字。
A B E G L I P c e f u y 2 8 9 6
I want to open this file which I can do from我想打开这个文件,我可以从
f = open("/home/someuser/Documents/alphabets.txt")
for word in f.read().split():
print(word)
But I want the random words to be printed from those alphabets.但我希望从这些字母表中打印随机单词。
I want words starting with 8 characters with every alphabets in it.我想要以 8 个字符开头的单词,其中包含每个字母。 Like permutation combination
像排列组合
None any word should be left from combination none should be repeated.没有任何单词应该从组合中留下任何单词都不应该重复。 How can I do this ??
我怎样才能做到这一点 ??
Thanks in advance提前致谢
Use itertools.product
to get all the combinations.使用
itertools.product
获取所有组合。
>>> alphabet = "ABCDEF"
>>> words = [''.join(x) for x in itertools.product(alphabet, repeat=3)]
>>> words
['AAA', 'AAB', ... 'FFE', 'FFF']
>>> len(words)
216
For getting random words, you can random.shuffle
that list and pop
elements from it (no repeats), or use random.choice
(with repeats)为了获得随机单词,您可以
random.shuffle
列表并从中pop
元素(无重复),或使用random.choice
(有重复)
>>> random.choice(words)
'EFA'
>>> random.shuffle(words)
>>> words.pop()
'CAD'
However, exhaustively generating all the 4,294,967,296 eight-letter-words from your alphabet will take very long.但是,从您的字母表中详尽地生成所有 4,294,967,296 个八字母单词需要很长时间。 If you just need a few random samples, it would be simpler to just join 8 random letters from the alphabet.
如果您只需要几个随机样本,只需加入字母表中的 8 个随机字母会更简单。
>>> [''.join(random.choice(alphabet) for _ in range(8)) for _ in range(5)]
['28GLIGB9', 'PE8uyLue', '6c8eGByA', 'BLucIuuf', 'fEeBf9Bf']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.