按字长索引 [英] Index by word length
问题描述
zymosans
zymoscope
zymoses
...
我希望能够输出一个文件每个字长自动使用此程序。像这样:
1letterwords.txt
2letterwords.txt
等等。
我昨天开始玩python ...我搜索了网站和这个网站,没有想到什么。
我想要一些关于如何从这个特定的编程问题开始的指针。
提前感谢!
(为了弄清楚,hangman游戏会在所请求的wordlength文件中打开一个随机行,相当显着地降低了性能影响。)
获取随机文件行可能不是您想要做的任何事情,或者将它们保留在列表中,和/或dict应该是数百万字的。
您可以通过遍历所有单词并将其添加到列表种子defaultdict中来存储单词长度列表:
从集合导入defaultdict
导入随机
wordsByLength = defaultdict(列表)
所有词中的单词:
wordsByLength [len(word)]。 append(word)
然后每当你需要一个随机字,你可以做:
randomLen = random.choice(wordsByLength.keys())
randomWord = random.choice(wordsByLength [randomLen])
或者您可以将randomLen替换为speci你想要的长度。
My aim was to simply make a hangman game. However, I have been slightly over-ambitious. I want to ask the user to input how long they want the word. Then choose a random word of that length. To index an entire dictionary of that length would take far too long on each iteration. So. I have a dictionary, formatted like so:
zymosans
zymoscope
zymoses
...
I would like to be able output a file for each 'length of word' automatically using this program. Like this:
1letterwords.txt
2letterwords.txt
and so forth.
I started python...yesterday. I searched both the web and this site and came up with nothing. I would like some pointers as to how to start with this specific programming problem. Thanks in advance! (To clarify, the hangman game would open a random line in the requested wordlength file, reducing performance impact...fairly dramatically.)
Getting random lines of files is probably not what you want to do either ... keeping them in a list and/or dict should be fine even for millions of words.
you can store list of words by their length by iterating over all your words and adding them to a list seeded defaultdict:
from collections import defaultdict
import random
wordsByLength = defaultdict( list )
for word in allWords:
wordsByLength[ len(word) ].append( word )
Then whenever you need a random word you can do:
randomLen = random.choice( wordsByLength.keys() )
randomWord = random.choice( wordsByLength[ randomLen ] )
Or you can replace randomLen with the specified length you wanted.
这篇关于按字长索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!